Skip to content

Instantly share code, notes, and snippets.

@dhrytsenko
Created March 31, 2017 15:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhrytsenko/76b8ff46bbefb61837d1af5b15914098 to your computer and use it in GitHub Desktop.
Save dhrytsenko/76b8ff46bbefb61837d1af5b15914098 to your computer and use it in GitHub Desktop.
Mongodb query
db.users.aggregate(
// Pipeline
[
// Stage 1
{
$match: {
"email": "nightquestd@gmail.com"
}
},
// Stage 2
{
$unwind: { "path": "$access" }
},
// Stage 3
{
$project: { "roleId": "$access.id", "role": "$access.role", "email": "$email" }
},
// Stage 4
{
$lookup: {
"from" :"accounts",
"localField": "roleId",
"foreignField": "_id",
"as": "accounts"
}
},
// Stage 5
{
$lookup: {
"from" :"crews",
"localField": "roleId",
"foreignField": "_id",
"as": "crews"
}
},
// Stage 6
{
$lookup: {
"from" :"boats",
"localField": "roleId",
"foreignField": "_id",
"as": "boats"
}
},
// Stage 7
{
$unwind: {
"path": "$boats",
"preserveNullAndEmptyArrays": true
}
},
// Stage 8
{
$unwind: {
"path": "$crews",
"preserveNullAndEmptyArrays": true
}
},
// Stage 9
{
$unwind: {
"path": "$accounts",
"preserveNullAndEmptyArrays": true
}
},
// Stage 11
{
$group: { "_id": "$_id",
"role": {
"$addToSet": "$role"
},
"email" : {
"$first": "$email"
},
"accounts": {
"$addToSet" :"$accounts"
},
"boats": {
"$addToSet": "$boats"
},
"crews": {
"$addToSet": "$crews"
}
}
},
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment