Removing specific elements from an array using MongoDB

I am developing a web application using Codeigniter and MongoDB. Users can upload files, and other users can comment on them.

I store comments in an array with comments in the main document file. Everything is fine, but how can I remove specific comments from an array?

I can not use ID as a key, since the user can add several comments. How would you recommend me to do this?

This is my array of comments:

"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" } ], 
+34
mongodb codeigniter
Jan 28 2018-12-12T00:
source share
3 answers

If you can identify a comment item by matching a user ID, name, or comment, you can delete this comment using the update() command with the $pull modifier along with the corresponding condition.

If you cannot do as described above, include a unique identifier in the comments (for example, UUID ).

To delete a comment, do the following:

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

If you are using an identifier that is preferred:

 db.coll.update({<cond to identify document}, {$pull: {'comments': {'id': <id>}}} ) 
+56
Jan 29 '12 at 18:41
source share

maybe you can delete the comment on the time ' created_at ', because the time is unique.

 $db.coll.update({cond to identify document},{$pull:{'comments':{'created_at':<>}}}) 
+3
Feb 17 '14 at 5:01
source share

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

 $comment_id = new MongoID(); 

Now you can delete comments by id using $ pull + $ update, e.g. @smoorthy.

0
Aug 12 '17 at 10:51 on
source share



All Articles