mongodb distinct
时间: 2023-09-09 21:07:24 浏览: 104
mongodb分片
MongoDB distinct is a method that is used to retrieve a unique list of values from a specified field of a collection. The distinct function returns an array of unique values from the specified field. It can be used to find the unique values of any field in a collection, including nested fields.
The syntax for using the distinct method in MongoDB is as follows:
```
db.collection.distinct(field, query)
```
- field: The name of the field for which the unique values are to be retrieved.
- query (optional): A document that specifies the query criteria. Only documents that match the query criteria will be considered for the distinct operation.
For example, if we have a collection "users" with the following documents:
```
{ "_id": 1, "name": "John", "age": 30 }
{ "_id": 2, "name": "Mary", "age": 25 }
{ "_id": 3, "name": "John", "age": 35 }
{ "_id": 4, "name": "Peter", "age": 30 }
```
To get the list of unique names, we can use the following query:
```
db.users.distinct("name")
```
This will return an array with the following values:
```
[ "John", "Mary", "Peter" ]
```
Note that the distinct method only works on a single field at a time. If we want to get the unique combination of two fields, we can use the aggregation framework instead.
阅读全文