Skip to content

Instantly share code, notes, and snippets.

@filipkrw
Created February 21, 2022 11:11
Show Gist options
  • Save filipkrw/34a8bb7ac6e894138ac6e18e66b02a31 to your computer and use it in GitHub Desktop.
Save filipkrw/34a8bb7ac6e894138ac6e18e66b02a31 to your computer and use it in GitHub Desktop.
/**
* 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