Created
February 21, 2022 11:11
-
-
Save filipkrw/34a8bb7ac6e894138ac6e18e66b02a31 to your computer and use it in GitHub Desktop.
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
/** | |
* With `authors` schema: { _id, name } and `books` schema: { _id, name, authorId }, | |
* select all authors with all their books. | |
*/ | |
// Simple way | |
db.authors.aggregate([ | |
{ | |
$lookup: { | |
from: "books", | |
localField: "_id", | |
foreignField: "authorId", | |
as: "books", | |
}, | |
}, | |
]); | |
// Equivalent, but more verbose; supports more complex cases | |
db.authors.aggregate([ | |
{ | |
$lookup: { | |
from: "books", | |
let: { id: "$_id" }, // $_id here is author._id, used in the pipeline below as $$id | |
pipeline: [ | |
{ | |
$match: { | |
$expr: { | |
$and: [ | |
{ $eq: ["$authorId", "$$id"] }, // $authorId here is permision.authorId | |
// possible other conditions here | |
], | |
}, | |
}, | |
}, | |
], | |
as: "books", | |
}, | |
}, | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment