Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all the non distinct values of a field in mongodb

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.

like image 229
bor Avatar asked Mar 30 '14 05:03

bor


People also ask

How do I filter distinct values in MongoDB?

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.

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

What is $Not in MongoDB?

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.

What is the use of distinct in MongoDB?

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.


1 Answers

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.

like image 72
Neil Lunn Avatar answered Sep 28 '22 06:09

Neil Lunn