Skip to content

Instantly share code, notes, and snippets.

@spencern
Last active December 28, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spencern/7531616 to your computer and use it in GitHub Desktop.
Save spencern/7531616 to your computer and use it in GitHub Desktop.
Using the MongoDB Aggregation framework to count the total number of likes among all users within a collection
db.users.aggregate(
[
{ $unwind : "$likes" },
{ $group : { _id : "$likes", number : { $sum : 1 } } },
{ $sort : { number : -1 } },
{ $limit : 10 }
]
);
{
"result" : [
{
"_id" : "mcei5Ycf9Fv3MMcfE",
"number" : 13
},
{
"_id" : "TFXdgcLcpRJaLcTrC",
"number" : 12
},
{
"_id" : "bzvPFrsqypBsM4otx",
"number" : 12
}
],
"ok" : 1
}
{ "_id" : "LGWEH8eGsPqYfvFm5",
"profile" : {
"firstName" : "Spencer",
"headline" : "Web Application Developer",
"lastName" : "Norman"
},
"dislikes" : [
"5hkWyLEBNTdrbFuko",
"QpKhWgFPcteYrz4CF",
"Ye6JFr6es5w7wCAPG",
"2nxJh8LP6YdtaRhoB",
"8hiRMNctzauggqgca",
"W4WHDuvFzQ8ETf8LB",
"YJfpzNj6b7YtN4ALa",
"LZnKWfsnhz5ex9apJ",
"KpsD84DvAHb2kaCiE",
"B3DF2EwqzYFNChY3d",
"u2n4grwb37dx44hgo",
"iK9LFefZHNqxFe6s7"
],
"likes" : [
"stWyympYqtDFH2Myh",
"jZiZ6gi4fFcRi3Gga",
"5suDFYZkK4zWvtrsq",
"hRqFZxALzXr2DthsZ",
"MLkfG5K69oJGz6A5a",
"yF2yQgeDWaMFxqvWe",
"g3sa2onpPRuZYfYvN"
]
}
db.users.aggregate(
[
{ $unwind : "$dislikes" },
{ $group : { _id : null, number : { $sum : 1 } } }
]
);
db.users.aggregate(
[
{ $unwind : "$likes" },
{ $group : { _id : null, number : { $sum : 1 } } }
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment