Y
Y
Young_nigilist2021-03-15 19:29:00
MongoDB
Young_nigilist, 2021-03-15 19:29:00

How to merge 3 MongoDB collections?

I have 3 collections:

Restaurants
RaUDF.png

Menu
mJxMo.png

Products
ITXBI.png

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
                 ...
           }, ...]
   }, ...]
 ...


I wrote a query like this:
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"
        }
    },
])

But it doesn't display the menu title.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Young_nigilist, 2021-03-15
@Young_nigilist

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 question

Ask a Question

731 491 924 answers to any question