mongodb query: how to get unique entries

ε祈祈猫儿з 提交于 2019-12-13 20:24:19

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/11028320/mongodb-query-how-to-get-unique-entries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!