How to MongoDB- Update & Delete document

In this guide, we are learning how to update & delete document from collections in MongoDB.

Update document in MongoDB

In MongoDB, update() method is used to update or modify the existing documents of a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.


     db.collection.update(query, update, options)


Consider the mycollection has the following data.

Mycollection Data
       "course": "MongoDB",  "category": "Database", "by": "lauyou"
       "course": "MySQL", "category": "Database", "by": ""
       "course": "Java", "category": "Programming", "by": ""


The following example will update Category “Programming” to “Programming language”.

Update query
     >db.mycollection.update({'category':'Programming'},{$set:{'category':'Programming language'}})
     { "_id" : ObjectId(3645369881331adf45ecd), "course": "MongoDB",  "category": "Database", "by": "lauyou"}
     { "_id" : ObjectId(3645369881331adf45ece), "course": "MySQL", "category": "Database", "by": ""}
     { "_id" : ObjectId(3645369881331adf45ecf), "course": "Java", "category": "Programming language", "by": ""}


Delete Document in MongoDB

The db.collection.remove() method can have one of two syntaxes. The remove() method can take a query document and an optional justOne boolean:

     db.collection_name.remove (DELETION_CRITERIA)

To remove all documents in a collection, call the remove method with an empty query document


     db.mycollection.remove( { } )

To remove a document that matches a specific condition, call the remove() method with the <query> parameter.


     db.mycollections.remove( { course : "Java" } )

Above example will remove all documents from the mycollection where the course field is equal to Java.

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...