Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save dcortesnet/67e47fd50c42b4a5e0a3370ec43e4014 to your computer and use it in GitHub Desktop.
MongoDB lookup N:M
// Orders collection
{
"_id" : ObjectId("634312b873d381100e27b8ea"),
"company" : "Microsoft",
"products" : [
ObjectId("634312f073d381100e27b8ec"),
ObjectId("634312f073d381100e27b8ed")
]
},
{
"_id" : ObjectId("634312b873d381100e27b8eb"),
"company" : "Apple",
"products" : [
ObjectId("634312f073d381100e27b8ed")
]
}
// Products collection
{
"_id" : ObjectId("634312f073d381100e27b8ec"),
"name" : "Mouse logitech",
"orders" : [
ObjectId("634312b873d381100e27b8ea")
]
},
{
"_id" : ObjectId("634312f073d381100e27b8ed"),
"name" : "Keyboard logitech",
"orders" : [
ObjectId("634312b873d381100e27b8ea"),
ObjectId("634312b873d381100e27b8eb")
]
}
// Query( can be queried from both endsm the example only products )
db.getCollection("products").aggregate({
$lookup: {
from: "orders",
localField: "orders",
foreignField: "_id",
as: "orders"
}
}
)
// Result
{
"_id" : ObjectId("634312f073d381100e27b8ec"),
"name" : "Mouse logitech",
"orders" : [{
"_id": ObjectId("634312b873d381100e27b8ea"),
"company": "Microsoft",
"products": [
ObjectId("634312f073d381100e27b8ec"),
ObjectId("634312f073d381100e27b8ed")
]
}
]
},
{
"_id" : ObjectId("634312f073d381100e27b8ed"),
"name" : "Keyboard logitech",
"orders" : [{
"_id": ObjectId("634312b873d381100e27b8ea"),
"company": "Microsoft",
"products": [
ObjectId("634312f073d381100e27b8ec"),
ObjectId("634312f073d381100e27b8ed")
]
},
{
"_id": ObjectId("634312b873d381100e27b8eb"),
"company": "Apple",
"products": [
ObjectId("634312f073d381100e27b8ed")
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment