Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

mongodb update multiple Array elements using db.update()

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...