0

I compiled 2 update queries by referring to related stackoverflow answers, however, it doesn't seem to work, query updates all elements while only elements matching the criteria are expected to update.

Document:

[
  {
    "_id": 259,
    "members": [
      {
        "email": "[email protected]",
        "added_by": "javapedia.net",
        "status": "pending"
      },
      {
        "email": "[email protected]",
        "added_by": "javapedia.net",
        "status": "pending"
      },
      {
        "email": "[email protected]",
        "status": "pending"
      }
    ]
  }
]

Query1: Using elemMatch operator, mongodb playground: https://mongoplayground.net/p/4cNgWJse86W

db.collection.update({
  _id: 259,
  "members": {
    "$elemMatch": {
      "email": {
        "$in": [
          "[email protected]",
          "[email protected]"
        ]
      }
    }
  }
},
{
  "$set": {
    "members.$[].status": "active"
  }
},
{
  "multi": true
})

Query2: using $in, mongodb playground : https://mongoplayground.net/p/tNu395B2RFx

db.collection.update({
  _id: 259,
  "members.email": {
    "$in": [
      "[email protected]",
      "[email protected]"
    ]
  }
},
{
  "$set": {
    "members.$[].status": "active"
  }
},
{
  "multi": true
})

Expected result: only one element with [email protected] status should be updated to active.

Actual result: both queries update all records.

3
  • also, include a sample document, $elemMatch looks rare to me Commented Jan 11, 2021 at 6:20
  • yyou could do "members.email":{$in..." Commented Jan 11, 2021 at 6:21
  • @turivishal, I may need to update multiple docs, in the example, I just covered only one doc. Commented Jan 11, 2021 at 6:23

1 Answer 1

2

Is this what you're looking for?

db.collection.update({
  _id: 259,  
},
{
  "$set": {
    "members.$[el].status": "active"
  }
},
{
  arrayFilters: [
    {
      "el.email": {
        $in: [
          "[email protected]",
          "[email protected]"
        ]
      }
    }
  ]
})
  • You can put the initial conditions back if needed, I just keep this short (and to me they make no sense).

  • multi:true isn't needed for one document

  • Maybe better semantically to use updateOne()

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.