To retrieve distinct values for a field in MongoDB, you can use the distinct
method in the MongoDB shell or in a MongoDB driver.
Here’s an example using the MongoDB shell:
db.collectionName.distinct("fieldName")
Replace collectionName
with the name of the collection you want to query and fieldName
with the name of the field for which you want to retrieve distinct values.
For example, if you have a collection called users
and you want to retrieve distinct values for the city
field, you can use the following command:
db.users.distinct("city")
This will return an array of all the distinct values for the city
field in the users
collection.
You can also add additional query criteria to filter the results. For example, if you only want to retrieve distinct values for the city
field where the state
field is equal to "CA"
, you can use the following command:
db.users.distinct("city", { state: "CA" })
This will return an array of all the distinct values for the city
field in the users
collection where the state
field is equal to "CA"
.