Skip to content

Instantly share code, notes, and snippets.

@anandsunderraman
Last active November 19, 2018 20:42
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 anandsunderraman/cc231e1f32ccbd203076aa1a3c3624d6 to your computer and use it in GitHub Desktop.
Save anandsunderraman/cc231e1f32ccbd203076aa1a3c3624d6 to your computer and use it in GitHub Desktop.
Mongo db multiple groupBy
//given a set of documents
var db = [
{
"store": {
"storeId": "1",
"storeName: "A"
},
"audit": {
"createdBy": "ME"
}
},
{
"store": {
"storeId": "1",
"storeName: "A"
},
"audit": {
"createdBy": "YOU"
}
},
{
"store": {
"storeId": "2",
"storeName: "B"
},
"audit": {
"createdBy": "YOU"
}
}
];
//and I want a mongo query to get all store ids that were created by ME and YOU
db.stores.aggregate([
{
$group: {
_id: {storeId: "$store.storeId", source: "$audit.createdBy"},
count: { $sum: 1}
}
},
{
$group: {
_id: "$_id.storeId",
count: { $sum: 1}
}
},
{
$match: {
count: { $gte: 2}
}
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment