Answer the question
In order to leave comments, you need to log in
How to merge 3 MongoDB collections?
I have 3 collections:
Restaurants
Menu
Products
The
product IDs are in the Menu; The menu IDs are in Restaurants.
How to display such a document?
{
...
menu:[{
_id
name
products:[{
_id
name
...
}, ...]
}, ...]
...
const restaurant = await Restaurant.aggregate([
{
"$match": { _id: ObjectId(req.params.id) }
},
{
"$lookup": {
"from": "menus",
"localField": "menu",
"foreignField": "_id",
"as": "menu",
}
},
{
"$lookup": {
"from": "products",
"localField": "menu.products",
"foreignField": "_id",
"as": "menu.products"
}
},
])
Answer the question
In order to leave comments, you need to log in
It turned out to be done like this:
const restaurant = await Restaurant.aggregate([
{
"$match": { _id: ObjectId(req.params.id) }
},
{
"$lookup": {
"from": "menus",
"localField": "menu",
"foreignField": "_id",
"as": "menu",
}
},
{ "$unwind": { "path": "$menu", "preserveNullAndEmptyArrays": true } },
{
"$lookup": {
"from": "products",
"localField": "menu.products",
"foreignField": "_id",
"as": "menu.products"
}
},
{
"$group": {
"_id": "$_id",
"name": { "$first": "$name" },
"hours": { "$first": "$hours" },
"image": { "$first": "$image" },
"phones": { "$first": "$phones" },
"takeAway": { "$first": "$takeAway" },
"description": { "$first": "$description" },
"address": { "$first": "$address" },
"user": { "$first": "$user" },
"menu": { "$push": "$menu" }
}
}
])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question