首页 > 解决方案 > 如何组合 3 个集合 MongoDB?

问题描述

我有 3 个系列:餐厅、菜单和产品。

它们的结构:

餐厅

菜单

产品

我想用嵌套数组进行查询。并尝试:

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"
        }
    },
])

但此查询返回没有菜单名称的数据:

"menu": {
    "products": [
        {
            "_id": "604f349280a17606402211d3",
            "price": 6,
            "image": "https://i.pinimg.com/736x/00/67/1e/00671e890191ecfeaf680cbecd3acf3e.jpg",
            "name": "Toast with banana",
            "description": "210g, Composition: Bread, Nutella, Banana",
            "user": "604f349280a17606402211d0",
            "__v": 0,
            "createdAt": "2021-03-15T10:18:58.220Z",
            "updatedAt": "2021-03-15T10:18:58.220Z"
        },...]

刚开始学习mongodb,所以不是很懂。请帮忙写一个请求。

如果我写错了,对不起,英语不是我的母语 :)

标签: node.jsmongodbmongodb-query

解决方案


原来是这样的

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" }
        }
    }
])

推荐阅读