我正在使用 Codeigniter 和 MongoDB 开发一个 Web 应用程序。 用户可以上传文件,其他用户可以对其发表评论。
我将注释存储在主文件文档中称为注释的数组中。 这一切都很好,但我怎样才能从数组中删除特定的评论?
我不能使用 ID 作为键,因为用户可以添加多个评论。怎么会 你建议我可以做到吗?
这是我的评论数组:
"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"
}
],
最佳答案
如果您可以通过匹配用户 ID、名称或评论来识别评论项目 -- 那么您可以使用带有 $pull
修饰符的 update()
命令以及合适的条件。
如果您无法按照上述方式进行操作,请在评论中包含唯一 id(如 UUID
)。
要删除评论,请执行以下操作:
db.coll.update({<cond to identify document}, {$pull: {'comments': {'name': <name>}}} )
如果你使用id,这是首选:
db.coll.update({<cond to identify document}, {$pull: {'comments': {'id': <id>}}} )
https://stackoverflow.com/questions/9048424/