使用 MongoDB 从数组中删除特定项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9048424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing specific items from array with MongoDB
提问by Jonathan Clark
I am developing a web app using Codeigniter and MongoDB. The users can upload files and other users can comment on them.
我正在使用 Codeigniter 和 MongoDB 开发 Web 应用程序。用户可以上传文件,其他用户可以对其发表评论。
I store the comments in an array called comments in the main file document. This is all fine but how can I remove specific comments from the array?
我将注释存储在主文件文档中名为 comments 的数组中。这一切都很好,但如何从数组中删除特定的注释?
I cannot use ID as key since a user can add multiple comments. How would you recommend that I can do it?
我不能使用 ID 作为键,因为用户可以添加多个评论。你怎么建议我能做到?
This is my comment array:
这是我的评论数组:
"comments": [
{
"user_id": ObjectId("4f240b433dc7937d68030000"),
"user_name": "james",
"user_comment": "This is a comment",
"created_at": "2012-01-2821: 20: 44"
},
{
"user_id": ObjectId("4f240b433dc7937d68030000"),
"user_name": "mandy",
"user_comment": "This is another comment",
"created_at": "2012-01-2821: 31: 07"
}
],
回答by rsmoorthy
If you can identify the comment item by matching userid, name or comment -- then you can remove that comment using update()
command with $pull
modifier along with the appropriate condition.
如果您可以通过匹配用户 ID、名称或评论来识别评论项目——那么您可以使用update()
带有$pull
修饰符的命令以及适当的条件来删除该评论。
If you cannot do as above, include an unique id in the comments (like UUID
).
如果你不能像上面那样做,请在评论中包含一个唯一的 id(如UUID
)。
To delete the comment, do the following:
要删除评论,请执行以下操作:
db.coll.update({<cond to identify document}, {$pull: {'comments': {'name': <name>}}} )
If you use the id, which is preferred:
如果您使用 id,这是首选:
db.coll.update({<cond to identify document}, {$pull: {'comments': {'id': <id>}}} )
回答by kevin
maybe you can remove comment by its 'created_at
' time, as the time is unique.
也许您可以按其“ created_at
”时间删除评论,因为时间是唯一的。
$db.coll.update({cond to identify document},{$pull:{'comments':{'created_at':<>}}})
回答by Burak ?ztürk
I think, you have add mongodb id to each comment when insert it. You can create a new mongodb id like this;
我认为,您在插入时已将 mongodb id 添加到每个评论中。您可以像这样创建一个新的 mongodb id;
$comment_id = new MongoID();
Now, you can delete comments by id with $pull + $update like @smoorthy's answer.
现在,您可以使用 $pull + $update 通过 id 删除评论,就像@smoorthy 的回答一样。