📅  最后修改于: 2023-12-03 15:32:56.419000             🧑  作者: Mango
MongoDB provides a convenient way to count the number of distinct documents in a collection or field using the distinct
method.
db.collection.distinct(fieldName, query)
Where:
fieldName
: the name of the field to count distinct values in.query
(optional): the selection criteria for the documents to count. This can be used to filter the documents before counting the distinct values.Given the following documents in a users
collection:
[
{ name: "Alice", age: 25, gender: "female" },
{ name: "Bob", age: 30, gender: "male" },
{ name: "Charlie", age: 25, gender: "male" },
{ name: "Dave", age: 35, gender: "male" },
{ name: "Eve", age: 30, gender: "female" }
]
To count the number of distinct ages in the collection, we can use the following command in the MongoDB shell:
db.users.distinct("age")
This will return an array of distinct ages:
[25, 30, 35]
We can also count the number of distinct genders for users over the age of 25:
db.users.distinct("gender", { age: { $gt: 25 } })
This will return an array of gender values for users over the age of 25:
["male", "female"]
MongoDB's distinct
method provides a simple way to count the number of distinct values in a collection or field. By using the query
parameter, we can also filter the documents before counting the distinct values.