mongoose - MongoDB groupby query -
i have colletions containing records
{ "type" : "me", "tid" : "1" } { "type" : "me", "tid" : "1" } { "type" : "me", "tid" : "1" } { "type" : "you", "tid" : "1" } { "type" : "you", "tid" : "1" } { "type" : "me", "tid" : "2" } { "type" : "me", "tid" : "2"} { "type" : "you", "tid" : "2"} { "type" : "you", "tid" : "2" } { "type" : "you", "tid" : "2"} i have want result below
[ {"tid" : "1","me" : 3,"you": 2}, {"tid" : "2","me" : 2,"you": 3} ] i have tried group and; aggregate queries doesn't required result format.
below group query.
db.coll.group({ key: {tid : 1,type:1}, cond: { tid : { "$in" : [ "1","2"]} }, reduce: function (curr,result) { result.total = result.total + 1 }, initial: { total : 0} }) it result
[ {"tid" : "1", "type" : "me" ,"total": 3 }, {"tid" : "1","type" : "you" ,"total": 2 }, {"tid" : "2", "type" : "me" ,"total": 2 }, {"tid" : "2","type" : "you" ,"total": 3 } ] following aggregate query
db.coll.aggregate([ {$match : { "tid" : {"$in" : ["1","2"]}}}, {$group : { _id : {tid : "$tid",type : "$type"},total : {"$sum" : 1}}} ]) gives following result
{ "result" : [ {"_id" : {"tid" : "1","type" : "me"},"total" : 3}, {"_id" : {"tid" : "2","type" : "me" },"total" : 2}, {"_id" : {"tid" : "2","type" : "you"},"total" : 3} ] "ok" : 1 } it possible obtain specified result or have manipulation in code.
thanks
if change aggregation this:
db.so.aggregate([ { $match : { "tid" : { "$in" : ["1", "2"] } } }, { $group : { _id : { tid : "$tid", type : "$type" }, total : { "$sum" : 1 } } }, { $group : { _id : "$_id.tid", values: { $push: { type: "$_id.type", total: '$total' } } } } ]) then output is:
{ "result" : [ { "_id" : "1", "values" : [ { "type" : "you", "total" : 2 }, { "type" : "me", "total" : 3 } ] }, { "_id" : "2", "values" : [ { "type" : "me", "total" : 2 }, { "type" : "you", "total" : 3 } ] } ], "ok" : 1 } although not same want, going closest can get. , in application, can pull out values in same like out of it.
just keep in mind, in general can not promote value (you, me) key — unless key of limited set (3-4 items max).
Comments
Post a Comment