Last active
November 19, 2018 20:42
-
-
Save anandsunderraman/cc231e1f32ccbd203076aa1a3c3624d6 to your computer and use it in GitHub Desktop.
Mongo db multiple groupBy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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