【问题标题】:Updating one single record in array inside Mongo Collection在 Mongo 集合中更新数组中的一条记录
【发布时间】:2020-12-29 02:47:05
【问题描述】:

大家好,我正在尝试添加一些字段并将现有字段更新到现有的 mongodb 文档数组。因为我是 mongo 的新手,所以我不太清楚如何操作数组内的嵌套文档。我的数组就像

    "productVersions" : [ 
    {
        "productVersion" : "1.0",
        "active" : true,
        "effectiveDate" : "01/09/2020",
        "versionDescription" : "Initial version"
    }, 
    {
        "productVersion" : "2.0",
        "active" : true,
        "effectiveDate" : "01/09/2020",
        "versionDescription" : "Initial version"
    }
]

首先我想找到正确的 productVersion,然后在该 productVersion 中更新现有字段,如果字段不存在则添加它。 下面是我想添加到 productVersion2 的一些字段,可以看出有效日期已经存在,必须更新,其余字段应该添加。

      {signatureId: 123,
      signatureURL: 'www.abc.com',
      effectiveDate: "01/09/2020",
      configurationStatus: "active",
      name: "john"} 

非常感谢任何帮助或想法。谢谢

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query nosql


    【解决方案1】:

    您可以使用$ operator 来更新数组。如果该字段已存在,则更新该字段的值,如果添加了非新字段

    db.collection.update(
      { "productVersions.productVersion": "2.0" },
      {
        $set: {
          "productVersions.$.signatureId": 123,
          "productVersions.$.signatureURL": "www.abc.com",
          "productVersions.$.effectiveDate": "01/09/2020",
          "productVersions.$.configurationStatus": "active",
          "productVersions.$.name": "john",
        },
      }
    );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多