mongodb - mongo group and count with condition -
i'm trying group set of documents , count them based on value. example
{ "_id" : 1, "item" : "abc1", "value" : "1" } { "_id" : 2, "item" : "abc1", "value" : "1" } { "_id" : 3, "item" : "abc1", "value" : "11" } { "_id" : 4, "item" : "abc1", "value" : "12" } { "_id" : 5, "item" : "xyz1", "value" : "2" } here group "item" , in return count how many times "value" bigger 10 , how many times smaller. so:
{ "item": "abc1", "countsmaller": 2, "countbigger": 1} { "item": "xyz1", "countsmaller": 1, "countbigger": 0} a plain count achieved $aggregate, how can achieve above result?
what need $cond operator of aggregation framework. 1 way want be:
db.foo.aggregate([ { $project: { item: 1, lessthan10: { // set 1 if value < 10 $cond: [ { $lt: ["$value", 10 ] }, 1, 0] }, morethan10: { // set 1 if value > 10 $cond: [ { $gt: [ "$value", 10 ] }, 1, 0] } } }, { $group: { _id: "$item", countsmaller: { $sum: "$lessthan10" }, countbigger: { $sum: "$morethan10" } } } ]) note: have assumed value numeric rather string.
output:
{ "result" : [ { "_id" : "xyz1", "countsmaller" : 1, "countbigger" : 0 }, { "_id" : "abc1", "countsmaller" : 2, "countbigger" : 2 } ], "ok" : 1 }
Comments
Post a Comment