[英]How to remove an Item from an Mongodb array documents
I have the following mongodb collection named Posts with document like following: 我有以下名为Posts的mongodb集合,其文档如下所示:
{
"_id" : "111",
"comments" : [
{
"replyPost" : "aaaa",
"username" : "John Doe"
},
{
"replyPost" : "bbbb",
"username" : "Jane Smith"
},
{
"replyPost" : "cccc",
"username" : "Jane Smith"
},
{
"replyPost" : "dddd",
"username" : "Jane Smith"
}
]
}
I am trying to remove an array item with the replyPost: "cccc" so the result would be: 我正在尝试使用ReplyPost删除数组项:“ cccc”,因此结果将是:
{
"_id" : "111",
"comments" : [
{
"replyPost" : "aaaa",
"username" : "John Doe"
},
{
"replyPost" : "bbbb",
"username" : "Jane Smith"
},
{
"replyPost" : "dddd",
"username" : "Jane Smith"
}
]
}
I have tried .update method with $pull refering to mongodb document https://docs.mongodb.com/manual/reference/operator/update/pull/ 我已经尝试使用$ pull的.update方法引用mongodb文档https://docs.mongodb.com/manual/reference/operator/update/pull/
Posts.update(
{_id: this._id},
{ $pull: { comments: { replyPost:"cccc"} } }
);
which don't seem to be working. 似乎不起作用。 can anyone see the problem?
谁能看到这个问题?
See if you're getting the right _id. 看看您是否获得了正确的_id。 It's in string format.
它是字符串格式。
I tried the same in mongo shell. 我在mongo shell中尝试了相同的方法。 It worked for me.
它为我工作。
Here's the log: 这是日志:
> db.posts.insert({
... "_id" : "111",
... "comments" : [
... {
... "replyPost" : "aaaa",
... "username" : "John Doe"
... },
... {
... "replyPost" : "bbbb",
... "username" : "Jane Smith"
... },
... {
... "replyPost" : "cccc",
... "username" : "Jane Smith"
... },
... {
... "replyPost" : "dddd",
... "username" : "Jane Smith"
... }
... ]
... })
WriteResult({ "nInserted" : 1 })
> db.posts.update({_id:'111'},{$pull:{comments:{replyPost:'cccc'}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.posts.findOne()
{
"_id" : "111",
"comments" : [
{
"replyPost" : "aaaa",
"username" : "John Doe"
},
{
"replyPost" : "bbbb",
"username" : "Jane Smith"
},
{
"replyPost" : "dddd",
"username" : "Jane Smith"
}
]
}
If you are using mongoose, you can do: 如果您使用猫鼬,则可以执行以下操作:
db.posts.remove({replyPost: 'cccc'}, function(err) {
})
The first parameter can be any mongoose query expression. 第一个参数可以是任何猫鼬查询表达式。 All matches will be removed from db.
所有匹配项将从数据库中删除。
See mongoose remove 见猫鼬删除
Tested Works Fine: 经过测试的作品良好:
Posts.update((
{"_id" : "111"},
{ $pull: {comments: {"replyPost" : "cccc"}} },
{ multi: true }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.