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

197
Views
Update object values inside array where id is equal to inside Array

Supposedly I want to update the object values of array of a document, but first I will need to look for its id first, heres the structure of document

{
_id: ObjectId('12312')
notifications: [
       {
         _id: ObjectId('1')
          status: 'unread'
       },
       {
         _id: ObjectId('2')
          status: 'unread'
       },
       {
         _id: ObjectId('3')
          status: 'unread'
       }
    ]
}


I want to update the status of notifications under that user where the objectId must be equal to inside the result array

result = 
  [
  new ObjectId("1"),
  new ObjectId("2"),
  ]

this should yield this result after the update

{
_id: ObjectId('12312')
notifications: [
       {
         _id: ObjectId('1')
          status: 'read'
       },
       {
         _id: ObjectId('2')
          status: 'read'
       },
       {
         _id: ObjectId('3')
          status: 'unread'
       }
    ]
}

Heres what Ive done so far but Im not getting the result i need

  const updateuser = await User.updateMany({_id:idofuser, "notifications._id": { $in : result }},{
     $set: {
            "notifications.$.status": "read",
         }
   })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use $map to iterate through notifications and use $cond and $mergeObjects to perform the conditional update.

db.collection.update({
  "_id": "12312"
},
[
  {
    "$set": {
      "notifications": {
        "$map": {
          "input": "$notifications",
          "as": "n",
          "in": {
            "$cond": {
              "if": {
                "$in": [
                  "$$n._id",
                  [
                    "1",
                    "2"
                  ]
                ]
              },
              "then": {
                "$mergeObjects": [
                  "$$n",
                  {
                    "status": "read"
                  }
                ]
              },
              "else": "$$n"
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Here is the Mongo Playground for your reference.

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