Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is remove an expensive operation in MongoDB?

Part of my site migration to MongoDB is migration of messaging system. I'm trying to figure out whether I should be actually removing the records from the collection or mark them as removed using some bool field, when the user wants to remove the message - the site will be high load so I'm concerned about performance (and not concerned about disk space).

Any ideas?

like image 319
Andrey Avatar asked May 22 '11 05:05

Andrey


People also ask

What is remove in MongoDB?

MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed.

What is difference between remove and delete in MongoDB?

deleteMany: command returns a boolean as true if the operation runs fine with the write concern and returns false if we disable the write concern. Also, it returns the deletedCount which contains the deleted document's number. Remove: command returns the WriteResult.

Does removing all collections in a database also remove the database in MongoDB?

Yes, to all.


1 Answers

Edit: this answer is a historical artifact from 2011 and it refers to the old MMAPv1 engine which was removed in 2019. However, as the comments note, remove is a one time operation and will be always cheaper than always checking a flag so remove is still the best option regardless of the storage engine internals.

tl;dr: remove.

MongoDB stores the data in a double linked list and so removing results is adjusting two links, the next link of the previous document and the previous link of the next document. There is no autocompacting. Updating, if you have a value already stored, happens in place, changing one value. Now... you think, great, update one int instead of two pointers, surely faster! Not so -- you now need to index on this flag and creating indexes is "slow".

like image 146
chx Avatar answered Sep 29 '22 14:09

chx