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

522
Views
Update nested object in array MongoDB

I need to find and update documents with category that corresponding to the query. Array could contain mo than one corresponding id.

Query:

{
 "ids": ["61f1cda47018c60012b3dd01", "61f1cdb87018c60012b3dd07"],
 "userId": "61eab3e57018c60012b3db3f"
}

I got collection with documents like:

`{

   "_id":{"$oid":"61f1cdd07018c60012b3dd09"},
   "expenses":[
     {"category":"61eafc104b88e154caa58616","price":"1111.00"},                  
     {"category":"61f1cdb87018c60012b3dd07","price":"2222.00"}, 
     {"category":"61f1cda47018c60012b3dd01","price":"1241.00"}, 
     {"category":"61f1cdb87018c60012b3dd07","price":"111.00"}
   ],
   "userId":"61eab3e57018c60012b3db3f"
 }`

my method:

  async myMethod(ids: [string], userId: string) {
try {
  const { ok } = await this.ExpensesModel.updateMany(
    {"userId": userId, "expenses.category": { $in: ids }},
    {$set: {"expenses.$.category": "newCategoryID"}}
  );
  return ok
} ........

I path array of ids ["61f1cda47018c60012b3dd01","61f1cdb87018c60012b3dd07","61f1cdb87018c60012b3dd07"] and userId, this code update only 1 category by document.

So can i made it with mongo build in methods? or i need to find matching document and update it it by my self and after that update or insert;

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Update with arrayFilters

db.collection.update({
  "expenses.category": {
    $in: [
      "61f1cda47018c60012b3dd01",
      "61f1cdb87018c60012b3dd07"
    ]
  }
},
{
  $set: {
    "expenses.$[elem].category": "61eab3e57018c60012b3db3f"
  }
},
{
  arrayFilters: [
    {
      "elem.category": {
        $in: [
          "61f1cda47018c60012b3dd01",
          "61f1cdb87018c60012b3dd07"
        ]
      }
    }
  ]
})

mongoplayground

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!