Collection contains a pair of strings Obj.a and Obj.b, find out the sum of all unique pairs?
Note Obj{a:"abc",b:"xyz"} is equivalent to Obj{a:"xyz",b:"abc"}, although they are two separate documents.
db.bade.aggregate([ | |
{$group: { _id: "$_id", a: { $push: "$a" }, b: { $push: "$b"}, c: { $first: "$c" }}}, | |
{$project: { d: { $setUnion: ["$a", "$b"]}, c: 1 } }, | |
{$unwind: "$d"}, | |
{$sort: { d: 1}}, | |
{$group: { _id: "$_id", d: { $push: "$d"}, c: { $max: "$c" } }}, | |
{$group: { _id: "$d", c: { $sum: "$c"}}} | |
]); |
{ "_id" : [ "efg", "xyz" ], "c" : 30 } | |
{ "_id" : [ "abc", "tuv" ], "c" : 10 } | |
{ "_id" : [ "abc", "xyz" ], "c" : 15 } | |
{ "_id" : [ "hij", "xyz" ], "c" : 9 } | |
{ "_id" : [ "abc", "hij" ], "c" : 15 } | |
{ "_id" : [ "klm", "xyz" ], "c" : 1 } | |
{ "_id" : [ "opq", "xyz" ], "c" : 20 } |
var aaas = [{a:"abc",b:"xyz",c:10},{a:"xyz",b:"abc",c:5},{a:"efg",b:"xyz",c:10},{a:"xyz",b:"efg",c:20},{a:"abc",b:"tuv",c:0},{a:"tuv",b:"abc",c:10},{a:"abc",b:"hij",c:15},{a:"hij",b:"xyz",c:9},{a:"klm",b:"xyz",c:1},{a:"opq",b:"xyz",c:10},{a:"xyz",b:"opq",c:10}]; | |
for (i in aaas) { | |
db.bade.save(aaas[i]); | |
} |