使用MongoDB从数组中删除特定项

Jon*_*ark 35 codeigniter mongodb

我正在使用Codeigniter和MongoDB开发一个Web应用程序.用户可以上传文件,其他用户可以对其进行评论.

我将注释存储在主文件文档中名为comments的数组中.这一切都很好,但我如何从数组中删除特定的注释?

我不能使用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"
        }
    ],
Run Code Online (Sandbox Code Playgroud)

rsm*_*thy 58

如果您可以通过匹配用户ID,名称或注释来标识注释项,那么您可以使用update()$pull修饰符的命令以及适当的条件来删除该注释.

如果您不能如上所述,请在评论中包含唯一ID(例如UUID).

要删除评论,请执行以下操作:

db.coll.update({<cond to identify document}, {$pull: {'comments': {'name': <name>}}} )
Run Code Online (Sandbox Code Playgroud)

如果您使用id,则首选:

db.coll.update({<cond to identify document}, {$pull: {'comments': {'id': <id>}}} )
Run Code Online (Sandbox Code Playgroud)