Skip to content

Instantly share code, notes, and snippets.

@dcortesnet
Created October 9, 2022 19:15
Show Gist options
  • Select an option

  • Save dcortesnet/a8708e3438c5e71009b25f9aa5eb061b to your computer and use it in GitHub Desktop.

Select an option

Save dcortesnet/a8708e3438c5e71009b25f9aa5eb061b to your computer and use it in GitHub Desktop.
MongoDB lookup 1:N
// Authors Collection
{
"_id" : ObjectId("63430b9e73d381100e27b8e9"),
"name" : "J. K. Rowling",
"books" : [
ObjectId("63430b8a73d381100e27b8e7"),
ObjectId("63430b8a73d381100e27b8e8")
]
}
// Books Collection
{
"_id" : ObjectId("63430b8a73d381100e27b8e7"),
"name" : "Philosopher's Stone"
},
{
"_id" : ObjectId("63430b8a73d381100e27b8e8"),
"name" : "Chamber of Secrets"
}
// Query
db.getCollection("authors").aggregate({
$lookup: {
from: "books",
localField: "books",
foreignField: "_id",
as: "books"
}
})
// Result
{
"_id" : ObjectId("63430b9e73d381100e27b8e9"),
"name" : "J. K. Rowling",
"books" : [{
"_id": ObjectId("63430b8a73d381100e27b8e7"),
"name": "Philosopher's Stone"
},
{
"_id": ObjectId("63430b8a73d381100e27b8e8"),
"name": "Chamber of Secrets"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment