简体   繁体   English

通过聚合将数据从一个 mongo 文档添加到不同的 mongo 文档

[英]Adding data from one mongo document to different mongo document with aggreagation

This situation is a little confusing, so I will do my best to explain with this example.这种情况有点混乱,所以我会尽力用这个例子来解释。

Lets say I have an object (mongoDb document) that looks like:假设我有一个 object(mongoDb 文档),它看起来像:

{
  _id: 0989sd7f987123bnkmsdfv,
  name: 'Item-004',
  itemId: 004,
  date: 10/11/1960,
  color: 'green',
  quantity: 21,
  listOfItems: [
   {
     itemId: 001, 
     itemName: 'Item-001',
     color: 'blue'
   },
   {
     itemId: 002, 
     itemName: 'Item-002',
     color: 'orange'
   },
   {
     itemId: 003, 
     itemName: 'Item-003',
     color: 'purple'
   }
  ]
}

This is an object in the items collection.这是items集合中的 object。 listOfItems is an array that is comprised of other items in the same collection, but the problem is that the array doesn't have enough details about the items. listOfItems是一个由同一集合中的其他项目组成的数组,但问题是该数组没有关于这些项目的足够详细信息。 Every Item has a name , date , itemId , color , quantity , and listOfItems array.每个 Item 都有一个namedateitemIdcolorquantitylistOfItems数组。 How can I write an aggregation query to add those fields to the item in the listOfItems array.如何编写聚合查询以将这些字段添加到listOfItems数组中的项目。

end result/ goal:最终结果/目标:

{
_id: 0989sd7f987123bnkmsdfv,
  name: 'Item-004',
  itemId: 004,
  date: 10/11/1960,
  color: 'green',
  quantity: 21,
  listOfItems: [
   { 
     itemId: 001, 
     name: 'Item-001',
     date: 12/12/1996,
     color: 'blue',
     quantity: 33,
   },
   {
     itemId: 002, 
     name: 'Item-002',
     date: 08/11/2021,
     color: 'orange',
     quantity: 1045,
   },
   {
     itemId: 003, 
     name: 'Item-003',
     date: 03/30/1998
     color: 'purple'
     quantity: 9,
   }
  ]
}

Try this:尝试这个:

db.collection.aggregate([
  {
    "$unwind": "$listOfItems"
  },
  {
    "$lookup": {
      "from": "collection",
      "localField": "listOfItems.itemId",
      "foreignField": "itemId",
      "as": "listOfItems"
    }
  },
  {
    "$unwind": "$listOfItems"
  },
  {
    "$unset": "listOfItems.listOfItems"
  },
  {
    "$group": {
      "_id": {
        "_id": "$_id",
        name: "$name",
        itemId: "$itemId",
        date: "$date",
        color: "$color",
        quantity: "$quantity"
      },
      "listOfItems": {
        "$push": "$listOfItems"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$_id",
          {
            listOfItems: "$listOfItems"
          }
        ]
      }
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "_id",
      "whenMatched": "replace",
      
    }
  }
])

Here's the corresponding playground link .这是相应的游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM