How can I list all the non-distinct values of a field in a collection in mongodb? I found distinct command to find all the distinct values for the field but I want the opposite.
To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
MongoDB provides different types of comparison query operators and $nin (not in) operator is one of them. This operator is used to select those documents where the value of the field is not equal to any of the given value in the array and the field that does not exist.
distinct() considers each element of the array as a separate value. For instance, if a field has as its value [ 1, [1], 1 ] , then db. collection. distinct() considers 1 , [1] , and 1 as separate values.
You can do this using .aggregate()
db.collection.aggregate([
{ "$group": {
"_id": "$field",
"count": { "$sum": 1 }
}},
{ "$match": {
"count": { "$gt": 1 }
}}
])
Also see the SQL to Aggregate Mapping examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With