子数组内的Mongodb更新操作

Mongodb update operation inside sub array

本文关键字:更新 操作 Mongodb 数组      更新时间:2023-09-26

我对mongodb非常陌生,并且在更新操作中遇到了一些麻烦。这是文档:

{
    "username" : "amitverma",
    "notifications" : {
        "notification_add_friend" : [
            {
                "sender" : "macbook",
                "action" : "",
                "type" : "",
                "objectType" : "request",
                "objectUrl" : "",
                "isUnread" : true
            },
            {
                "sender" : "safari",
                "action" : "",
                "type" : "",
                "objectType" : "request",
                "objectUrl" : "",
                "isUnread" : true
            },
            {
                "sender" : "chrome",
                "action" : "",
                "type" : "",
                "objectType" : "request",
                "objectUrl" : "",
                "isUnread" : true
            }
        ]
    },
    "_id" : ObjectId("526598c86f45240000000001")
}
{
    "username" : "macbook",
    "notifications" : {
        "notification_add_friend" : [
            {
                "sender" : "amitverma",
                "action" : "",
                "type" : "",
                "objectType" : "a_r",
                "objectUrl" : "",
                "isUnread" : true
            }
        ]
    },
    "_id" : ObjectId("526598d06f45240000000002")
}

我想删除{"sender":"safari"}子数组"username":"amitverma"我已经尝试$elemMatch$set,但无法正确获取查询。

不想在此处使用$set,但$pull(请参阅文档),虽然您可以使用$elemMatch来进一步指定查询,但您不需要这样做。

以下内容将从与{"username": "amitverma"}匹配的文档子数组中提取所有带有{"sender": "safari"}的添加好友通知

db.yourcollection.update({"username": "amitverma"}, { 
  $pull: {"notifications.notifications_add_friend": {"sender": "safari"}}
})

至于您的评论,如果您想更新特定元素,请将$set$elemMatch位置运算符 $ 结合使用。 对于您的示例,如下所示:

db.yourcollection.update({
  "username": "amitverma", 
  "notifications.notifications_add_friend": {
    $elemMatch: {"sender": "safari"}
  }
}, {
  $set: {
    "notifications.notifications_add_friend.$.isUnread": false
  }
})