有什么方法可以让我在一个请求中返回多个计数?
而不是奔跑users.find({gender:"male"}).count();,231然后奔跑,users.find({gender:"female"}).count();得到416可以返回的东西{male:"231",female:"416"}。我知道 map reduce 可以做到这一点,这是我最好的选择吗?
Groupby在Aggregation框架中会做的伎俩
db.users.aggregate({$group:{_id:'$gender',count:{$sum:1}}})
RameshVel 是正确的。该$group命令可能是您正在寻找的。
例如,以下查询:
db.people.aggregate({$group: {_id: '$gender', total: { $sum : 1 }}})
将产生以下结果:
{
"result": [
{
"_id": "m",
"total": 49988
},
{
"_id": "f",
"total": 50012
}
],
"ok": 1
}
您可以在此处阅读有关 MongoDB 聚合框架的更多信息:http: //docs.mongodb.org/manual/applications/aggregation/
希望有帮助。