Created
April 3, 2017 13:03
-
-
Save bhargavkonkathi/cada19ad93401ee083f85e6bd47ebafe to your computer and use it in GitHub Desktop.
Mongodb Query
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
db.users.aggregate( | |
// Pipeline | |
[ | |
// Stage 1 | |
{ | |
$match: { | |
"email": "[email protected]" | |
} | |
}, | |
// 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 | |
// Stage 11 | |
{ | |
$group: { "_id": "$_id", | |
"role": { | |
"$addToSet": "$role" | |
}, | |
"email" : { | |
"$first": "$email" | |
}, | |
"accounts": { | |
"$addToSet" :"$accounts" | |
}, | |
"boats": { | |
"$addToSet": "$boats" | |
}, | |
"crews": { | |
"$addToSet": "$crews" | |
} | |
} | |
},{ | |
"$project":{ | |
"_id": 1, | |
"email": 1, | |
"role":1, | |
"access": { "$setUnion": ["$accounts", "$boats", "$crews" ] } | |
} | |
} | |
] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment