mongodb 查询:如何获取唯一条目 [英] mongodb query: how to get unique entries
问题描述
我有,假设有 100 行.在每个集合中,都有一个id"字段.假设 100 行,20 行的 'id' 为 10,30 行的 'id' 为 11,50 行的 'id' 为 12.我的查询应该返回:10 - 20 (计数)11 - 30 (计数)12 - 50(计数).
如何编写此查询?
如果您的集合名为foo",则以下内容将起作用.
<代码>>db.foo.group({键:{id:true},初始:{计数:0},减少:功能(文档,聚合器){聚合器计数 += 1;}})
会产生如下结果:
<预><代码>[{身份证":10,计数":20},{身份证":11,计数":30},{身份证":12,计数":50}]这里有关于 group() 的更多细节和一些例子:http://www.mongodb.org/display/DOCS/Aggregation
新的聚合框架要复杂得多.你可以在这里找到它:http://docs.mongodb.org/manual/applications/聚合/
I have, let's say 100 rows. In each collection, there is an 'id' field. Let's say of the 100 rows, 20 rows have an 'id' of 10, 30 rows have an 'id' of 11 and 50 rows have an 'id' of 12. My query should return: 10 - 20 (count) 11 - 30 (count) 12 - 50 (count).
How do I write this query?
If your collection is called "foo", the following will work.
> db.foo.group({
key: {id: true},
initial: {count: 0},
reduce: function(doc, aggregator) {
aggregator.count += 1;
}
})
It will produce results as follows:
[
{
"id" : 10,
"count" : 20
},
{
"id" : 11,
"count" : 30
},
{
"id" : 12,
"count" : 50
}
]
There is further detail on group(), and some examples, here: http://www.mongodb.org/display/DOCS/Aggregation
The new Aggregation Framework is substantially more sophisticated. You can find out about it here: http://docs.mongodb.org/manual/applications/aggregation/
这篇关于mongodb 查询:如何获取唯一条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!