相关疑难解决方法(0)

如何在mongodb中更新多个数组元素

我有一个Mongo文档,其中包含一系列元素.

我想重置.handled数组中所有对象的属性.profile= XX.

该文件采用以下形式:

{
    "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"),
    "user_id": "714638ba-2e08-2168-2b99-00002f3d43c0",
    "events": [{
            "handled": 1,
            "profile": 10,
            "data": "....."
        } {
            "handled": 1,
            "profile": 10,
            "data": "....."
        } {
            "handled": 1,
            "profile": 20,
            "data": "....."
        }
        ...
    ]
}
Run Code Online (Sandbox Code Playgroud)

所以,我尝试了以下内容:

.update({"events.profile":10},{$set:{"events.$.handled":0}},false,true)
Run Code Online (Sandbox Code Playgroud)

但是,它仅更新每个文档中第一个匹配的数组元素.(这是$的定义行为- 位置运算符.)

如何更新所有匹配的数组元素?

arrays mongodb mongodb-query

171
推荐指数
9
解决办法
10万
查看次数

更新了Mongoose更新嵌套数组元素

我有以下架构

UserSchema: Schema = new Schema({
  username: String,
  password: String,
  chat: [{
    lastSeen: { type: Date, default: Date.now },
    room: {
        type: Schema.Types.ObjectId, ref: 'ChatRoom'
    }
  }],
});
Run Code Online (Sandbox Code Playgroud)

我想对进行静态方法UserSchema,以便chat[i].lastSeen通过给定更新room _id

UserSchema.statics.lastSeen = 
function lastSeen(username: string, roomId: number, date: Date) {
   this.update({
    username: username,
    chat: {
        $elemMatch: {
            'room._id': roomId
        }
    }},
    {
        $set: { 'chat.$[???].lastSeen': date}
    });
}
Run Code Online (Sandbox Code Playgroud)

我找不到如何通过他的元素获取chat元素room._id然后进行更新。有什么帮助吗?

编辑

我的案子与建议的重复案类似但不相同,因为那里的人知道所有ids,而我不知道chat._id

javascript mongoose mongodb node.js typescript

0
推荐指数
1
解决办法
811
查看次数