Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"         }     ], 
like image 924
Jonathan Clark Avatar asked Jan 28 '12 20:01

Jonathan Clark


People also ask

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove a specific value from an index array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.


2 Answers

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>}}} ) 
like image 194
rsmoorthy Avatar answered Oct 02 '22 12:10

rsmoorthy


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':<>}}}) 
like image 22
kevin Avatar answered Oct 02 '22 11:10

kevin