子数组内的mongodb更新操作 [英] Mongodb update operation inside sub array

查看:41
本文介绍了子数组内的mongodb更新操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 mongodb 非常陌生,并且在更新操作方面遇到了一些麻烦.这是文件:

I am extremely new to mongodb and am facing a little trouble with an update operation. Here is the document:

{
    "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")
}

我想在 "username":"amitverma" 中删除带有 {"sender":"safari"} 的子数组我已经用 $set 尝试过 $elemMatch,但无法正确获取查询.

I want to remove the sub array with {"sender":"safari"} within "username":"amitverma" I have tried $elemMatch with $set, but just couldn't get the query correctly.

推荐答案

你不想在这里使用 $set,但是 $pull (查看文档),而您可以使用 $elemMatch 进一步指定您的查询,您不需要.

You don't want to use $set here, but $pull (see docs), and while you could use $elemMatch to further specify your query, you do not need to.

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

The following would pull all add friend notifications with {"sender": "safari"} from the sub array of documents matching {"username": "amitverma"}

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

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

As to your comment, if you wanted to update a particular element you would use $set in combination with $elemMatch and the positional operator $. For your example, something like:

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

这篇关于子数组内的mongodb更新操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆