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

115
Views
Update multiple elements of array in mongodb document with appropriate element of javascript array

I have array of objects with following structure:

const myArr = [{
'name':'question1',
'grade':6
},
{
'name':'question2',
'grade':7
}]

Question collection:

{
_id:623749f845844e7d273d801c,
questions:[
{
'name':'question1',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801m
},
{
'name':'question2',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801a
},
{
'name':'question3',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801f
}
]
}

I just want to update all objects in array questions in collection which i have provided in myArr array. So the desired result should be:

{
    _id:623749f845844e7d273d801c,
    questions:[
    {
    'name':'question1',
    'grade':6,
    'someInfo':'blabla',
    _id:623749f845844e7d273d801m
    },
    {
    'name':'question2',
    'grade':7,
    'someInfo':'blabla',
    _id:623749f845844e7d273d801a
    },
    {
    'name':'question3',
    'grade':10,
    'someInfo':'blabla',
    _id:623749f845844e7d273d801f
    }
    ]
}

What i've found so far:

I managed to update grade when i specify the question name with positional operator:

    await Prijave.updateOne(
    {
      _id: mongoose.Types.ObjectId(q_id),
      'questions.name': 'question1',
    },
    {
      $set: {
        'questions.$.grade': '10',
      },
    }
  )

But how to do this for every element in myArr ? I could make forEach loop which iterates through myArrand call updateOne for every element but i dont think it should be done that way because it will make multiple connection to database instead of one.

about 4 years ago · Juan Pablo Isaza
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!