MongoDB – Part 3 – CRUD Operations

By | April 2, 2018

 Agenda:  How to:

  1. Insert One record
  2. Bulk Insert
  3. Save
  4. Difference between Save and Insert

Insert One Record:

We can insert a record in a existing collection or write an insert without creating required collection. In this case MongoDB automatically creates the collection for you.

In the above example you can see we never created Assets collection but using insert on assets automatically creates the collection.

Bulk Insert:

It is all about inserting array of objects within [ ]

Count() function provides the number of rows in that collection.


Save command will do upsert i.e. if the id does not exist it will perform insert operation otherwise update operation.


We use update method to update the record as given in the below example

When we want to do a true update, never use Save. In the following example you can identify yourself on why not to use Save when the requirement is just Update.

Through update I can update selective columns and leave other columns undisturbed. Wherein Save() just replaces the document based on the matching id. In the above example by upsert Save() removed the desc column itself.


Remove based on a criteria :

Remove all records


Instead of removing all records as above we can simply drop the collection.

Difference between remove() and Drop() are as follows :

  1. Drop is quick when compared to remove() as remove() function invokes lot of house keeping works within MongoDB
  2. On remove({}) We still have the collection. By drop() we remove the collection itself.
  3. Remove doesn’t undo the indexes where in drop() removes all indexes

Leave a Reply

Your email address will not be published. Required fields are marked *