MongoDB - Remove Query

In MongoDB, the db.collection.remove() method allows us to remove documents from a collection. This is similar to the DELETE from statement in standard SQL.

There are several options you must pass to the document query when removing documents. Uou can remove all documents in the collection, delete only those documents that match a specific condition or you can choose to remove a single document.

Remove All Documents or Drop?

In order to remove all documents in a collection, we must enter the Mongo shell and pass the query an empty document. It should be noted that the remove() method does not remove the collection's indexes.

connecting to test  
> db.people.remove( {} );
WriteResult({ 'nRemoved' : 25 })  

Our remove query operation displays a write result with a message that 25 documents were successfully removed from our people collection.

It may be faster and more efficient to use the db.collection.drop() method instead of remove(). The drop() method will remove all indexes and then re-create the collection and rebuild all of the collection indexes. Unlike SQL's DROP TABLE statement, MongoDB keeps track of all of the collection indexes in the event the collection must be repaired or rebuilt.

Remove Documents matching a Specific Condition

To remove documents from a collection that match a specific condition, you can simply call the remove() method with the query parameters. In this example, we pass a user type to our people collection.

connecting to: test  
> db.people.remove( { 'type' : 'user' });
WriteResult({ 'nRemoved' : 5 })  

The write result shows a success message and the remove operation resulted in 5 documents being deleted.

Here we deleted all users from the people collection.

Remove a Single Document that matches a Specific Condition

In MongoDB, we can not only delete multiple documents that match a specific condition, e can also delete a single document. To remove a single document, simply call the remove() method, pass the query document condition and set the justOne parameter to True (or 1).

connecting to: test  
> db.people.remove( { 'type' : 'moderator' }, 1 );
WriteResult({ 'nRemoved' : 1 })  

Our write result displays a success message that 1 document from the people collection was removed.

Alternatively, the MongoDB findAndModify() method can and should be used to remove a single document by a set order of matching parameters.

In the next installment, I will take a brief look at the MongoDB findAndModify() method before jumping into writing tests for test-driven development (TDD) methodologies and concepts in Python.

I also want to spend a bit more time with PyMongo before defining our REST framework in Django for the app we're building.

Craig Derington

Full Stack Developer. Linux, Docker, Python, Celery, Flask, Django, Go, MySQL, MongoDB and Git. Modern, secure, high-performance applications capable of processing millions of transactions a day.

comments powered by Disqus