问题
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