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

153
Views
update the nested array in mongodb using node js

I need to update a particular element of the nested array in mongoDB

My mongoDB data looks like below. I need to match the value accessid and name to update the status. The input content has

{"accessid" : 1627047023995, "name" : Name 09, "status" : 100 }

The input content may belong to any level

  {
        "_id" : ObjectId("60fac46ffcbf5287248460a9"), 
        "levelone" : [ 
            {
                "level" : [ 
                    {
                        "name" : "Name 01",
                        "status" : 5
                    }, 
                    {
                        "name" : "Name 02",
                        "status" : 0
                    }, 
                    {
                        "name" : "Name 03",
                        "status" : 0
                    } 
                ], 
                "accessid" : "1627047023995" 
            }, 
            {
                "level" : [ 
                    {
                        "name" : "Name 09",
                        "status" : 5
                    }, 
                    {
                        "name" : "Name 15",
                        "status" : 3
                    } 
                ], 
                "accessid" : "1627047023995" 
            }
        ],
        "createdAt" : ISODate("2021-07-23T13:30:23.995Z") 
    }

I have tried to update the status, but it is updating only the first index value - name: Name 01 status. Please guide to resolve the issue.

collections.updateOne({
  'levelone.level.accessid': accessid,
  'levelone.level.name': name
}, { '$set': { 'levelone.$.level.status': status } }).exec();
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you can use arrayFilters positional update,

  • query with $elemMatch to filter the main document
  • arrayFilters to define a variable for accessid and b for name
await collections.updateOne({
  levelone: {
    $elemMatch: {
      accessid: accessid,
      "level.name": name
    }
  }
},
{
  $set: {
    "levelone.$[a].level.$[b].status": status
  }
},
{
  arrayFilters: [
    { "a.accessid": accessid },
    { "b.name": name }
  ]
})

Playground

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!