36

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"
        }
    ],
0

3 Answers 3

60

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>}}} )
Sign up to request clarification or add additional context in comments.

6 Comments

Sounds interesting. Can I let mongoDB assign a UUID? If yes, how?
Nope. For values within your document, as in this case, you need to generate UUID. PHP has uniqid(), which you can also use.
Thanks for a thorough answer. The docs on this one are lackluster.
but how can I add an index for the fields in an object of an array?
Can you show how we can do this using Linq for Mongo DB c# ?
|
4

maybe you can remove comment by its 'created_at' time, as the time is unique.

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

1 Comment

Multiple users can post in the same second, though, so i'd generate a unique id for each comment.
0

I think, you have add mongodb id to each comment when insert it. You can create a new mongodb id like this;

$comment_id = new MongoID();

Now, you can delete comments by id with $pull + $update like @smoorthy's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.