MongoDB query for all documents with a unique field

I see many answers to the question "how do I get all the unique values ​​in the field?" who offer a method .distinct(). But this returns a simple array of these values. How to get all documents that have a unique field value?

[{age: 21, name: 'bob'}, {age: 21, name: 'sally'}, {age: 30, name: 'Jim'}] 
Query for unique age -->
[{age: 21, name: 'sally'}, {age: 30, name: 'Jim'}]
or
[{age: 21, name: 'bob'}, {age: 30, name: 'Jim'}]

Filtering the request after the fact is not an ideal solution, since I still want to choose $ limit and $ skip, as usual.

+5
source share
1 answer
> db.foo.insert([{age: 21, name: 'bob'}, {age: 21, name: 'sally'}, {age: 30, name: 'Jim'}])
> db.foo.count()
3
> db.foo.aggregate({ $group: { _id: '$age', name: { $max: '$name' } } }).result
[
    {
        "_id" : 30,
        "name" : "Jim"
    },
    {
        "_id" : 21,
        "name" : "sally"
    }
]
+3
source

All Articles