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

211
Views
How to update multiple objects in array in a single mongodb document using mongoose

I know that this can be a repeat question but none of the existing answers solved my problem.

I have a friendsSchema like below:

const friendsSchema = new mongoose.Schema({
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Player'
    },
    friends: [{
        friendId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Player'
        },
        isFromFacebook: {
            type: Boolean,
            default: false
        },
        thisFriendReceivedGiftTimeStamp: {
            type: Date,
            default: null
        },
        thisFriendSentGiftTimeStamp: {
            type: Date,
            default: null
        }
    }]
}, {
    timestamps: true
});

The client is sending me an array of friendsIds.

So, I want to find all objects in friends array which matches all friendsIds and update their thisFriendReceivedGiftTimeStamp to Date.now().

Consider the client is sending 100s of ids in friendsIds array, what will be the most efficient way to achieve the result.

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

db.collection.update({IF YOU WANT TO ADD QUERY ACCORDING TO OWNER FIELD PLEASE ADD HERE},
{
  "$set": {
    "friends.$[x].thisFriendReceivedGiftTimeStamp": new Date()
  }
},
{
  "arrayFilters": [
    {
      "x.friendId": {
        $in: [
          1,
          3,
          5
        ]
      }
    }
  ],
  "multi": true
})

arrayFilters should work great here. But I am not 100% sure about efficiency

Here is a working mongoplayground link

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!