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

我正在使用 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/

相关文章:

javascript - Mongoose 保存与插入与创建

mongodb - 在 Meteor 中运行示例的问题

node.js - Nodejs 中的 Mongodb 与 Postgres

node.js - Mongoose - 验证电子邮件语法

mongodb - 你如何告诉 Mongo 在限制结果之前对集合进行排序?

javascript - 在 Node.js 中进行同步 MongoDB 查询的正确方法是什么?

mongodb - 如何在 MongoDB shell 中中止正在运行的查询?

mongodb - 在 MongoDB 中执行搜索/投影时如何重命名字段?

mongodb - 聚合框架中的 $skip 和 $limit

shell - 为 MongoDB shell 设置默认数据库