Mongodb 在$lookup中使用嵌套属性

Mongodb 在$lookup中使用嵌套属性,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,假设我有一个Person对象。每个人有n个房子,每个房子里有m个房间。每个房间都有一个特殊的物品id,我也收集了这些物品。所以我的Person对象看起来有点像这样: person: { name: "Fictional Name", houses: [ { rooms: [ { itemId : "q23434c23" },{

假设我有一个Person对象。每个人有n个房子,每个房子里有m个房间。每个房间都有一个特殊的物品id,我也收集了这些物品。所以我的Person对象看起来有点像这样:

person: {
    name: "Fictional Name",
    houses: [
        {
            rooms: [
                {
                    itemId : "q23434c23"
                },{
                    itemId : "q34c356b5"
                },{...}
            ]
        },{...}
    ]
}
item: {
    _id: "q23434c23",
    type: "PLASTIC",
    description: "basic description"
}
现在,当我聚合我的person集合时,我尝试将所有这些
$lookup
项ID都放在其中,并将它们存储为变量。问题是我不知道怎么查。我尝试运行下面的代码,但它只适用于第一家:

db.persons.aggregate([
    {
       $lookup: {
           from: "items",
           localField: "houses.rooms.itemId",
           foreignField: "_id",
           as: "myItems"
       }
    },{
        $project: {
            name: 1,
            myItems: "$myItems"
        }
    }
])
编辑:项目看起来有点像这样:

person: {
    name: "Fictional Name",
    houses: [
        {
            rooms: [
                {
                    itemId : "q23434c23"
                },{
                    itemId : "q34c356b5"
                },{...}
            ]
        },{...}
    ]
}
item: {
    _id: "q23434c23",
    type: "PLASTIC",
    description: "basic description"
}

您可以使用下面的聚合

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

你的物品收藏在哪里?@AnthonyWinzlet我不明白这个问题。items集合与my person集合位于同一数据库中。请将
items
集合中的一些样本集合显示为well@AnthonyWinzlet好的,当然可以。但是如果我想在
“houses”
中包含
类型
描述
文件,那该怎么办呢?如果你能问一个新问题并提供适当的细节,那会更好。我一定会帮助你的