feat: add findDistinct operation (#13102)
Adds a new operation findDistinct that can give you distinct values of a
field for a given collection
Example:
Assume you have a collection posts with multiple documents, and some of
them share the same title:
```js
// Example dataset (some titles appear multiple times)
[
{ title: 'title-1' },
{ title: 'title-2' },
{ title: 'title-1' },
{ title: 'title-3' },
{ title: 'title-2' },
{ title: 'title-4' },
{ title: 'title-5' },
{ title: 'title-6' },
{ title: 'title-7' },
{ title: 'title-8' },
{ title: 'title-9' },
]
```
You can now retrieve all unique title values using findDistinct:
```js
const result = await payload.findDistinct({
collection: 'posts',
field: 'title',
})
console.log(result.values)
// Output:
// [
// 'title-1',
// 'title-2',
// 'title-3',
// 'title-4',
// 'title-5',
// 'title-6',
// 'title-7',
// 'title-8',
// 'title-9'
// ]
```
You can also limit the number of distinct results:
```js
const limitedResult = await payload.findDistinct({
collection: 'posts',
field: 'title',
sortOrder: 'desc',
limit: 3,
})
console.log(limitedResult.values)
// Output:
// [
// 'title-1',
// 'title-2',
// 'title-3'
// ]
```
You can also pass a `where` query to filter the documents.
This commit is contained in:
@@ -194,6 +194,27 @@ const result = await payload.count({
|
||||
})
|
||||
```
|
||||
|
||||
### FindDistinct#collection-find-distinct
|
||||
|
||||
```js
|
||||
// Result will be an object with:
|
||||
// {
|
||||
// values: ['value-1', 'value-2'], // array of distinct values,
|
||||
// field: 'title', // the field
|
||||
// totalDocs: 10, // count of the distinct values satisfies query,
|
||||
// perPage: 10, // count of distinct values per page (based on provided limit)
|
||||
// }
|
||||
const result = await payload.findDistinct({
|
||||
collection: 'posts', // required
|
||||
locale: 'en',
|
||||
where: {}, // pass a `where` query here
|
||||
user: dummyUser,
|
||||
overrideAccess: false,
|
||||
field: 'title',
|
||||
sort: 'title',
|
||||
})
|
||||
```
|
||||
|
||||
### Update by ID#collection-update-by-id
|
||||
|
||||
```js
|
||||
|
||||
Reference in New Issue
Block a user