简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM