0

I have this data :

{
  'id': '1',
  'object': [
     {'code': 'a'},
     {'code': 'b'},
     {'code': 'c'}
  ]
}

And this query :

db.test.update({
    'id': '1',
    'object': {
        '$elemMatch': {
            '$or': [
                {'code': 'b'},
                {'code': 'c'}
            ]
        }
    }
},
    {'$set':{'object.$.test':'ok'}}
)

Documents can contain one of these codes, both or none.
It works well with documents with one condition fulfilled.

In the case if there are 2 codes in the document, only the first one is updated :
I want to update both of them (code: 'b' AND code: 'c')

{
  'id': '1',
  'object': [
     {'code': 'a', 'test': 'ok'},
     {'code': 'b'}
  ]
}

This is what I want :

{
  'id': '1',
  'object': [
     {'code': 'a', 'test': 'ok'},
     {'code': 'b', 'test': 'ok'}
  ]
}

Thank you for helping.

1
  • 1
    the $ positional will update first matching element, for multiple elements update use arrayFilters. Commented Jun 21, 2021 at 9:27

1 Answer 1

2

You have to make use of $[identifier] update and pass the conditions in arrayFilters since $ will update only a single record as pointed by @turivishal

db.collection.update({
  "id": "1",
  "object.code": {
    "$in": [
      "b",
      "c"
    ]
  }
},
{
  "$set": {
    "object.$[elem].code": "ok"
  }
},
{
  arrayFilters: [
    {
      "elem.code": {
        "$in": [
          "b",
          "c"
        ]
      }
    }
  ],
},
)

Mongo Playground Sample Execution

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.