Update array element in mongo

后端 未结 1 462
长情又很酷
长情又很酷 2021-01-28 10:48

I want to update an array that I have in a mongo doc. The structure of which looks something like:

{
  _id: id,
  myArray: [
    {key1: val, key2: val, key3: va         


        
1条回答
  •  孤街浪徒
    2021-01-28 11:14

    When mongodb queries an array field it provides a positional operator $ which you can use to access a specific element in that array. You can use an elemMatch operator to search into the fields within an array of objects.

    Example:

    db.myCollection.find({
       _id: ObjectId("53b1a44350f148976b0b6044"),
       myArray: {
          $elemMatch: {key1: 'somevalue'}
       }
    }, {
       $set:{
          'myArray.$.key2': 'someOtherValue'
       }
    });
    

    See: http://docs.mongodb.org/manual/reference/operator/update/positional/

    0 讨论(0)
提交回复
热议问题