将数组连接到同一文档中的另一个 MongoDB

Concat array into other one inside same document MongoDB

有没有办法在嵌套字段中插入内容:“urls2.url_breed”在“url_alternative.url”中??我有很多文件要这样处理

    {  "_id": {    "$oid": "625f2900fe6aeb351381c3ff"  },  
    "breed": "Alaskan Malamute",  
    "origin": "United States (Alaska)",   
    "url_alternative": [
            {
              "urls": [
                "url23","url25"
              ]
            }
          ], 
    "url": "https://en.wikipedia.org/wiki/Alaskan_Malamute",  
    "img": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Alaskan_Malamute.jpg/300px-Alaskan_Malamute.jpg",
    "urls2": [
       {"_id": {"$oid": "627c04199569b8c2f566d15d"},
       "breed": "Alaskan Malamute",      
       "url_breed": [ "url1", "url2" ]}  
    ]}

期望的输出:

     {  "_id": {    "$oid": "625f2900fe6aeb351381c3ff"  },  
        "breed": "Alaskan Malamute",  
        "origin": "United States (Alaska)",   
        "url_alternative": [
                {
                  "urls": [
                    "url1","url2",
                    "url23","url25"
                  ]
                }
              ], 
        "url": "https://en.wikipedia.org/wiki/Alaskan_Malamute",  
        "img": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Alaskan_Malamute.jpg/300px-Alaskan_Malamute.jpg",
    
        ]}

有些情况下url_alternative是空的,但我还是想插入“urls2”的内容,因为这个总是填满的:

"url_alternative": [
        {
          "urls": [
            
          ]
        }
      ], 

由于您的高度嵌套结构,这在查询中可能会很复杂,但这个想法很简单。通过 $zip 构造 2 个数组的元组,迭代结果并使用 $concatArrays 将它们“展平为数组。

db.collection.update({},
[
  {
    $addFields: {
      "url_alternative.urls": {
        "$reduce": {
          "input": {
            "$reduce": {
              "input": {
                "$zip": {
                  "inputs": [
                    "$url_alternative",
                    "$urls2"
                  ]
                }
              },
              "initialValue": [],
              "in": {
                "$concatArrays": [
                  "$$value",
                  "$$this.urls",
                  "$$this.url_breed"
                ]
              }
            }
          },
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

这里是Mongo Playground供大家参考。