示例数据:
{ "category" : "abc" }
{ "category" : "abc", "ready": true }
{ "category" : "xyz" }
{ "category" : "foo", "ready": true }
{ "category" : "foo", "ready": true }
{ "category" : "foo" }
预期产出:
{
"abc": {
"count": 2,
"ready": 1
},
"xyz": {
"count": 1,
"ready": 0
},
"foo": {
"count": 3,
"ready": 2
}
}
此外,如果我可以选择提供迄今为止的日期或月份来制作这类统计数据,那将是很好的。
谢谢!
答案 0 :(得分:1)
你走了:
db.foo.aggregate([{
$group: {
_id: "$category",
count: { $sum: 1},
ready: {
$sum: {
$cond: {
if: "$ready",
then: 1,
else: 0
}
}
}
}
}])
返回:
/* 1 */
{
"_id" : "foo",
"count" : 3,
"ready" : 2
}
/* 2 */
{
"_id" : "xyz",
"count" : 1,
"ready" : 0
}
/* 3 */
{
"_id" : "abc",
"count" : 2,
"ready" : 1
}