Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB query for all documents with unique field

Tags:

mongodb

I see plenty of responses to the question "how do I get all of the unique values in a field?" which suggest the .distinct() method. But this returns a simple array of those values. How do I retrieve all of the documents which HAVE a unique value of a field?

[{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 a query after-the-fact is not an ideal solution, as I will still want to select, $limit, and $skip as usual.

like image 542
Sinetheta Avatar asked Oct 05 '22 03:10

Sinetheta


1 Answers

> 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"
    }
]
like image 169
A. Jesse Jiryu Davis Avatar answered Oct 13 '22 12:10

A. Jesse Jiryu Davis