Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Mongoose not updating multiple matches
[
  {
    "id": 1,
    "items": [
      {
        id: 15,
        score: 10
      },
      {
        id: 14,
        score: 100
      },
      {
        id: 12,
        score: 1
      }
    ]
  },
  {
    "id": 2,
    "items": []
  }
]

Now, I try to update items whose id is 14,15 & used the following query.

db.collection.update({
  "items.id": {
    $in: [
      14,
      15
    ]
  }
},
{
  $set: {
    "items.$.score": 444
  }
},
{
  multi: true
}
)

but it updated only the first match in items that is that is id with 15, what can be wrong?

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "id": 1,
    "items": [
      {
        "id": 15,
        "score": 444
      },
      {
        "id": 14,
        "score": 100
      },
      {
        "id": 12,
        "score": 1
      }
    ]
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "id": 2,
    "items": []
  }
]
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can do it with Positional identifiers $[]

db.collection.update({
  "items.id": {
    $in: [
      14,
      15
    ]
  }
},
{
  $set: {
    "items.$[element].score": 444
  }
},
{
  arrayFilters: [
    {
      "element.id": {
        $in: [
          14,
          15
        ]
      }
    }
  ],
  multi: true
})

try it here

over 4 years ago · Santiago Trujillo Report

0

Use arrayFilters with targeted array elements: here is the doc

db.collection.update({
  "id": 1
},
{
  "$set": {
    "items.$[ele].score": 20
  }
},
{
  arrayFilters: [
    {
      "ele.id": {
        "$in": [
          15,
          14
        ]
      }
    }
  ]
})

see play ground code https://mongoplayground.net/p/cdgu1aqLwsI

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!