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.
CodePudding user response:
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