在$ lookup

时间:2019-02-14 14:16:58

标签: mongodb mongodb-query aggregation-framework

假设我有一个Person对象。每个人的房屋数量为 n 个,每个房屋中的房屋数量为 m 个。在每个房间里都有一个特殊的物品ID,我也收藏了这些物品。所以我的Person对象看起来像这样:

person: {
    name: "Fictional Name",
    houses: [
        {
            rooms: [
                {
                    itemId : "q23434c23"
                },{
                    itemId : "q34c356b5"
                },{...}
            ]
        },{...}
    ]
}

现在,当我汇总我的 person 集合时,我尝试将$lookup中的所有这些itemId存储在其中,并将它们存储为变量。问题是我不知道如何查找它们。我尝试在下面运行代码,但仅适用于第一宫:

db.persons.aggregate([
    {
       $lookup: {
           from: "items",
           localField: "houses.rooms.itemId",
           foreignField: "_id",
           as: "myItems"
       }
    },{
        $project: {
            name: 1,
            myItems: "$myItems"
        }
    }
])

编辑:项目看起来像这样:

item: {
    _id: "q23434c23",
    type: "PLASTIC",
    description: "basic description"
}

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

db.persons.aggregate([
  { "$unwind": "$houses" }
  { "$lookup": {
    "from": "items",
    "localField": "houses.rooms.itemId",
    "foreignField": "_id",
    "as": "houses.rooms"
  }},
  { "$group": {
    "_id": "$_id",
    "houses": { "$push": "$houses" }
    "name": { "$first": "$name" }
  }}
])