我看到很多回答“如何在一个领域中获得所有独特价值?”的问题。这表明.distinct()
方法。但是这会返回这些值的简单数组。如何检索具有字段唯一值的所有文档?
[{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'}]
事后过滤查询不是一个理想的解决方案,因为我仍然会像往常一样选择,$ limit和$ skip。
答案 0 :(得分:3)
> 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"
}
]