MongoDb aggregate and group by two fields depending on values -
i want aggregate on collection type given. if type foo want grouping field author, if type bar want grouping user.
all should happen in 1 query.
example data:
{ "_id": 1, "author": { "somefield": "abc", }, "type": "foo" } { "_id": 2, "author": { "somefield": "abc", }, "type": "foo" } { "_id": 3, "user": { "somefield": "abc", }, "type": "bar" } this user field existing if type bar.
so that... tried express $or.
function () { var results = db.vote.aggregate( [ { $or: [ { { $match : { type : "foo" } }, { $group : { _id : "$author", sumauthor : {$sum : 1} } } }, { { $match : { type : "bar" } }, { $group : { _id : "$user", sumuser : {$sum : 1} } } } ] } ] ); homecoming results; } does have solution this?
i think can done
db.c.aggregate([{ $group : { _id : { $cond : [{ $eq : [ "$type", "foo"] }, "author", "user"] }, sum : { $sum : 1 } } }]); mongodb group mongodb-query aggregation-framework
No comments:
Post a Comment