MONGO DB updating nested array

时间:2019-02-20 19:50:43

标签: mongodb

Below Array this Exisiting in DataBase and
[{
    name: 'Courier Received by Investor',
    value: true
  },
  {
    name: 'Courier Sent By Investor',
    value: false
  },
  {
    name: 'Signed CA-Doc received',
    value: false
  },
  {
    name: 'Cheque/Payment Received',
    value: false
  },
  {
    name: 'Cancelled Cheque Received',
    value: false
  },
  {
    name: 'ID Proof Received',
    value: false
  },
  {
    name: 'Address Proof Received',
    value: false
  },
  {
    name: 'Signed CA pictures/scan received',
    value: false
  }
]


 I WANT TO UPDATE THESE BELOW FIELDS IN THE ABOVE ARRAY, CAN ANYONE HELP ME WITH THIS?


[{
    name: 'Courier Received by Investor',
    value: true
  },
  {
    name: 'Courier Sent By Investor',
    value: true
  },
  {
    name: 'Cheque/Payment Received',
    value: true
  }
]

1 个答案:

答案 0 :(得分:0)

您可以将arrayFiltersfiltered positional operator一起使用。

例如,假设您创建的文档具有以下结构(arrayField是用于保存数组值的字段名称):

{
    arrayField: [{
            name: 'Courier Received by Investor',
            value: true
        },
        {
            name: 'Courier Sent By Investor',
            value: false
        },
        {
            name: 'Signed CA-Doc received',
            value: false
        },
        {
            name: 'Cheque/Payment Received',
            value: false
        },
        {
            name: 'Cancelled Cheque Received',
            value: false
        },
        {
            name: 'ID Proof Received',
            value: false
        },
        {
            name: 'Address Proof Received',
            value: false
        },
        {
            name: 'Signed CA pictures/scan received',
            value: false
        }
    ]
}

您可以更新Courier Sent By Investor的所有条目,并将其设置为true,如下所示:

db.collection.update({}, {
    $set: {
        "arrayField.$[element].value": true
    }
}, {
    multi: true,
    arrayFilters: [{
        "element.name": "Courier Sent By Investor"
    }]
})