MongoDB查询具有唯一字段的所有文档 [英] MongoDB query for all documents with unique field
本文介绍了MongoDB查询具有唯一字段的所有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对如何在一个字段中获得所有唯一值"这个问题有很多回答.建议使用.distinct()
方法.但这将返回这些值的简单数组.如何检索所有具有字段唯一值的文档?
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'}]
事后过滤查询不是一个理想的解决方案,因为我仍然会像往常一样选择$ limit和$ skip.
Filtering a query after-the-fact is not an ideal solution, as I will still want to select, $limit, and $skip as usual.
推荐答案
> 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"
}
]
这篇关于MongoDB查询具有唯一字段的所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文