[英]Mongodb update operation inside sub array
I am extremely new to mongodb and am facing a little trouble with an update operation. 我对mongodb非常新,并且在更新操作方面遇到了一些麻烦。 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")
}
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. 我想在"username":"amitverma"
删除带有{"sender":"safari"}
的子数组"username":"amitverma"
我尝试使用$ set设置$ 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. 你不想在这里使用$set
,但是$pull
( 参见文档 ),虽然你可以使用$elemMatch
来进一步指定你的查询,但是你不需要。
The following would pull all add friend notifications with {"sender": "safari"}
from the sub array of documents matching {"username": "amitverma"}
以下内容将从匹配{"username": "amitverma"}
的文档子数组中添加{"sender": "safari"}
所有添加好友通知
db.yourcollection.update({"username": "amitverma"}, {
$pull: {"notifications.notifications_add_friend": {"sender": "safari"}}
})
As to your comment, if you wanted to update a particular element you would use $set
in combination with $elemMatch
and the positional operator $ . 至于你的评论,如果你想更新一个特定元素,你可以将 $set
与$elemMatch
和位置运算符$结合使用。 For your example, something like: 对于您的示例,例如:
db.yourcollection.update({
"username": "amitverma",
"notifications.notifications_add_friend": {
$elemMatch: {"sender": "safari"}
}
}, {
$set: {
"notifications.notifications_add_friend.$.isUnread": false
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.