使用 MongoDB 从数组中删除特定项目 [英] Removing specific items from array with MongoDB

查看:29
本文介绍了使用 MongoDB 从数组中删除特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing a web app using Codeigniter and MongoDB. The users can upload files and other users can comment on them.

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

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?

我不能使用 ID 作为键,因为用户可以添加多个评论.怎么会你建议我能做到吗?

I cannot use ID as key since a user can add multiple comments. How would you recommend that I can do it?

这是我的评论数组:

"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、名称或评论来识别评论项——那么您可以使用 update() 删除该评论带有 $pull 修饰符和适当条件的命令.

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(例如 UUID).

If you cannot do as above, include an unique id in the comments (like UUID).

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

To delete the comment, do the following:

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

如果您使用 id,这是首选:

If you use the id, which is preferred:

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

这篇关于使用 MongoDB 从数组中删除特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆