子数组内的Mongodb更新操作

时间:2013-10-21 21:25:24

标签: javascript node.js mongodb

我对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"的子数组 我用$ set尝试了$ elemMatch,但是无法正确获取查询。

1 个答案:

答案 0 :(得分:2)

您不希望在此使用$set,而是$pullsee docs),而可以使用$elemMatch进一步指定您的查询,您不需要。

以下内容将从匹配{"sender": "safari"}

的文档子数组中提取{"username": "amitverma"}的所有添加好友通知
db.yourcollection.update({"username": "amitverma"}, { 
  $pull: {"notifications.notifications_add_friend": {"sender": "safari"}}
})

关于您的评论,如果您想要更新特定元素,$setpositional operator $结合使用$elemMatch。对于您的示例,例如:

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