MongoDB:为某些值的$count返回0(聚合框架)
我有以下MongoDB查询:MongoDB:为某些值的$count返回0(聚合框架),mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有以下MongoDB查询: db.collection.aggregate([{ $match : { platform_id : ... } }, { $group: { _id: "$type", count: { $sum: 1 } } }]); $type的可能值为0或1 现在,如果有类型值为0或1的记录,我会得到0和1的计数 但是,如果所有记录都具有相同的类型(例如1),如何使0的计数也为0 从帖子上看,这似乎是不可能的。在这
db.collection.aggregate([{
$match : { platform_id : ... }
}, {
$group: {
_id: "$type",
count: { $sum: 1 }
}
}]);
$type的可能值为0或1
现在,如果有类型值为0或1的记录,我会得到0和1的计数
但是,如果所有记录都具有相同的类型(例如1),如何使0的计数也为0
从帖子上看,这似乎是不可能的。在这种情况下是真的吗?只有聚合不能实现您的目标。之后需要一些JS代码
var aggr = db.collection.aggregate([{
$match : { platform_id : ... }
}, {
$group: {
_id: {$ifNull : ["$type", 0]},
count: { $sum: 1 }
}
}]);
var result = aggr.toArray(); // mongo shell V2.6+
// var result = aggr.result; // mongo shell before V2.6
[{_id : 0, count : 0}, {_id : 1, count : 0}].forEach(function(e) {
var i = 0;
var len = result.length;
while (i < len && e._id != result[i]._id) ++i;
if (i >= len) result.push(e);
});
// result is the final.
这很接近。假设所有文档的类型都设置为1,但0是可接受的值。我如何让它返回[{'count':250','u id':1},{'count':0','u id':0}]?@okoboko,看来您已经修改了您的需求。我已经相应地更新了答案。