Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

codeigniter - Removing specific items from array with MongoDB

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

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?

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

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"
        }
    ],
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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>}}} )

If you use the id, which is preferred:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...