MongoDB - 迭代到对象数组并将字段更新为数组

MongoDB - Iterate to Array of objects and update the field as array

我是 MongoDB 的新手。我有一个包含多个文档的集合,其中特定文档具有嵌套数组结构。我需要遍历这个嵌套数组并更改迭代字段值的数据类型。

嵌套数组结构:

[
    {
        "identifier":{
            "type":"xxxx",
            "value":"1111"
        },
        "origin":"example.com",
        "score":8.0
    },
    {
        "identifier":{
            "type":"yyyyy",
            "value":"222"
        },
        "origin":"example.com",
        "score":8.0
    },
    {
        "identifier":{
            "type":"zzzzz",
            "value":"3333"
        },
        "origin":"https://olkdghf.com",
        "score":8.0
    }
]

问题是我需要在不替换现有字段值的情况下更改数据类型。但是我得到一个新的空值而不是原始值。

我的查询:

db.SourceEntityv8test.find({"hasIdentifier.identifier.type": {$exists:true}}).sort({_id:1}).skip(0).limit(100).forEach(function(x) 
    {
        db.SourceEntityv8test.update({_id: x._id}, {$set:{"hasIdentifier.$[].identifier.type":[]}} );
    });

预期输出:

[
    {
        "identifier":{
            "type":[xxxx],
            "value":"1111"
        },
        "origin":"example.com",
        "score":8.0
    },
    {
        "identifier":{
            "type":[yyyyy],
            "value":"222"
        },
        "origin":"example.com",
        "score":8.0
    },
    {
        "identifier":{
            "type":[zzzzz],
            "value":"3333"
        },
        "origin":"example.com",
        "score":8.0
    }
]

实现的输出:

[
    {
        "identifier":{
            "type":[],
            "value":"1111"
        },
        "origin":"example.com",
        "score":8.0
    },
    {
        "identifier":{
            "type":[],
            "value":"222"
        },
        "origin":"example.com",
        "score":8.0
    },
    {
        "identifier":{
            "type":[],
            "value":"3333"
        },
        "origin":"example.com",
        "score":8.0
    }
]

有点复杂。预计你需要在update with aggregation pipeline.

之前实现

概念:

  1. 通过 1.1.
  2. 更新整个 hasIdentifier 数组

1.1。将 hasIdentifier 数组中的每个文档与 1.1.1.

合并

1.1.1。将 identifier 对象与具有 type 数组的文档合并。

db.SourceEntityv8test.update({_id: x._id},
[
  {
    $set: {
      hasIdentifier: {
        $map: {
          input: "$hasIdentifier",
          in: {
            $mergeObjects: [
              "$$this",
              {
                "identifier": {
                  $mergeObjects: [
                    "$$this.identifier",
                    {
                      type: [
                        "$$this.identifier.type"
                      ]
                    }
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground