簡體   English   中英

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

預計 output:

[
    {
        "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
    }
]

取得output:

[
    {
        "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
    }
]

有點復雜。 預計您需要通過使用聚合管道更新來實現它。

概念:

  1. 通過1.1更新整個hasIdentifier數組。

1.1. hasIdentifier數組中的每個文檔與1.1.1合並。

1.1.1. identifier object 與數組type的文檔合並。

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

示例 Mongo 游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM