Monk Driver for MongoDB – How to Delete Documents?

Want create site? Find Free WordPress Themes and plugins.

This is the final part of the series where I’ll show you how to delete documents in the MongoDB database using the Monk Driver. I’ve chosen Monk as it has a simple interface, excellent processing time and does not require a schema structure. In case you have missed out on the previous ones, you can refer how to create documents, how to select documents and how to updated documents.

Moving forward. Let’s begin with how to delete documents and databases in MongoDB with Monk.

Connect to MongoDB using Monk, by firing the following lines of code.

const db = require('monk')('localhost/mydb')
const users = db.get('dbusers')

Deletion is an important part for every database schema. In MongoDB, deletion can be achieved by three methods – remove(), $unset() and $pull().

Let’s start the deletion process step-by-step –

To remove the database we have the following command.

db.dropDatabase(). This query will drop the selected database.

In order to remove a collection from a database, the below query will be executed.

db.collectionName.remove() //where collectionName is the name of collection to be deleted.

Now, for specific conditional deletion, we will fire the following query:


Ex: To delete all the documents having value greater than 90 we will fire a query, which will look like below:

Now coming to $unset (), we will perform the below operations.

For Deleting the particular element or subdocument, you can fire the following query.

var collection=db.get(‘collectionName’);
collection.find({},{$unset:{fieldname:1}}, function (err, doc, next) {
//do your operations

For Deleting a particular element or subdocument from all documents inside a collection, we can fire the following query.

collection.find({},{$unset:{fieldname:1}},{multi:true}, function (err, doc, next) {
//do your operations

Note: Once we use multi:true it unset particular fieldname from every document inside a collection.

Conditional deletion can also be achieved through pull method:

As the name suggests, the pull method will pull out all the values from the documents, if the condition is satisfied.
Example: if you have to pull out all the the records that match a particular _id in the collection, the below will query will be fired:

db.collectionName.update({},{$pull:fieldname:{_id:”id to be matched”}},{multi:true})

In above example fieldname is the name of field to be pulled out.
Note: multi:true will be used for pulling out all the data from the documents that matches the given condition.

That’s all for the Monk Driver for MongoDB series!

Did you find apk for android? You can find new Free Android Games and apps.


Related Posts

Leave A Comment