Monday, 15 June 2015

MongoDB: return 0 for $count of certain values (aggregation framework) -



MongoDB: return 0 for $count of certain values (aggregation framework) -

i have next mongodb query:

db.collection.aggregate([{ $match : { platform_id : ... } }, { $group: { _id: "$type", count: { $sum: 1 } } }]);

the possible values $type 0 or 1.

right now, count of 0s , 1s if there records either type value (0 or 1).

but, if records have same type (e.g. 1), how count of 0s 0?

from this post, looks might not possible. true in case?

only aggregate can not fulfill target. need js code after it.

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 = 0; var len = result.length; while (i < len && e._id != result[i]._id) ++i; if (i >= len) result.push(e); }); // result final.

mongodb aggregation-framework

No comments:

Post a Comment