在不同集合中的数组对象字段之间查找并获取单个元素

时间:2019-05-14 14:47:07

标签: mongodb aggregation-framework

我正在尝试从不同集合中的数组对象之间的查找中获取单个对象。

项目集合:

{  
   "_id":"5cd97a35e24f1a253e444605",
   "createdOn":"2019-05-13T14:07:10.971Z",
   "itemType":"text value",
   "fields":[  
      {  
         "_id":"5cd97a35e24f1a253e444606",
         "fieldConfigRef":"5cd97cbb566d432ac3ebb748",
         "value":"text value"
      }
   ],
   "__v":0
}

项目配置集合:

{  
   "_id":"5cd97cbb566d432ac3ebb747",
   "itemType":"Bolletta",
   "fields":[  
      {  
         "_id":"5cd97cbb566d432ac3ebb749",
         "name":"importo",
         "label":"Importo",
         "fieldType":"number",
         "fulltext":true
      },
      {  
         "_id":"5cd97cbb566d432ac3ebb748",
         "name":"emitettente",
         "label":"Emittente",
         "fieldType":"string",
         "fulltext":true
      }
   ],
   "__v":0
}

我可以通过_id和嵌套数组的fieldConfigRef属性将它们加入:

db.items.aggregate([
  {
    $match: {
      _id: ObjectId("5cd97a35e24f1a253e444605")
    }
  },
  {
    $lookup: {
      from: "itemconfigurations",
      localField: "fields.fieldConfigRef",
      foreignField: "fields._id",
      as: "itemconfig"
    }
  }
])

输出:

{
    "_id": "5cd97a35e24f1a253e444605"
    "createdOn": "2019-05-13T14:07:10.971Z"
    "itemType": "Bolletta"
    "fields": [
        {
            "_id": "5cd97a35e24f1a253e444606"
            "fieldConfigRef": "5cd97cbb566d432ac3ebb748"
            "value": "Eni Gas e Luce"
        }
    ]
    "__v": 0 
    "itemconfig": [
        {
            "_id": "5cd97cbb566d432ac3ebb747"
            "itemType": "Bolletta"
            "fields": [
                {
                    "_id": "5cd97cbb566d432ac3ebb749"
                    "name": "importo"
                    "label": "Importo"
                    "fieldType": "number"
                    "fulltext": true
                }
                {
                    "_id": "5cd97cbb566d432ac3ebb748"
                    "name": "emitettente"
                    "label": "Emittente"
                    "fieldType": "string"
                    "fulltext": true
                }
            ]
            "__v": 0
        }
    ]
}

如何在嵌套数组对象元素之间获取合并对象的单个数组?

0 个答案:

没有答案