如何使用 mongoose 在单个 mongodb 文档中更新数组中的多个对象

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

我知道这可能是一个重复问题,但 none 现有答案解决了我的问题。

我有一个 friendsSchema 如下所示:

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
});

客户正在向我发送 friendsIds.

的数组

所以,我想找到 friends 数组中匹配所有 friendsIds 的所有对象,并将它们的 thisFriendReceivedGiftTimeStamp 更新为 Date.now()

考虑客户端在 friendsIds 数组中发送 100 个 ID,什么是实现结果的最有效方法。

提前致谢。

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 在这里应该很好用。但我不是100%确定效率

这是一个有效的 mongoplayground link