【问题标题】:How to update a specified field having a given value in mongo db如何更新mongodb中具有给定值的特定字段
【发布时间】:2021-04-23 14:36:13
【问题描述】:

在这里我想更新给定的文档,如下所示

{
    
    "emailid": "xxx.gmail",
    
    "user_devices": [],
    "devices": [{
        "created_time": 1607153351,
        "token": 123
    },
    {
        "created_time": 1807153371,
        "token": 1345
    }]
}

这里我需要使用令牌 1345 更新现场设备,并使用一个新字段,如“Newfield”:“newfield”,最终输出如下所示

{
    
    "emailid": "xxx.gmail",
    
    "user_devices": [],
    "devices": [{
        "created_time": 1607153351,
        "token": 123
    },
    {
        "created_time": 1807153371,
        "token": 1345,
        "Newfield":"newfield"

    }]
}

如何像这样更新 mongo 数据库。提前感谢您的回答。

【问题讨论】:

    标签: mongodb mongodb-query insert-update


    【解决方案1】:
    db.products.update({
      "devices.token": 1345 //Matching condition
    },
    {
      $set: {
        "devices.$.t": 2 //Updates the matched element in the array
      }
    })
    

    您可以使用 positional operator - Reference 来完成此操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      相关资源
      最近更新 更多