Basic queries for CRUD operations in MongoDB

Posted By : Akash Sharma | 30-Jan-2013

Basic CRUD MongoDB

In this blog I am going to share some basic queries for mongoDB.

Creating a empty database and adding an authenticated User to that database:


>use mydb

//opens database with given name

//and sets this database as current DB.

//if this DB does not exit it will create an empty DB.

>db.addUser("userName", "password");

//this user can only access the current database i.e. mydb 

//Now exit from the mongoDB:


Now enter the mongoDB as authenticated user:

mongo -u username -p password       
//it opens DB at given IP with username and password

> j = { name : "sachin" , salary : 1000 , age : 20};


//creates a collection myCollection and insert a document in it.
//this collection is inserted in current DB.


collection in mongoDB is same as table in mysql.
document in mongoDB is same as row in mysql.
When you apply save method to a collection for the first time a new collection of that name is created and document is inserted into it.

In MongoDB there is no predefinition of fields (what would be columns in an RDBMS). There is no schema for fields within documents – the fields and their value datatypes can vary.
MongoDB collections are essentially named groupings of documents. You can think of them as roughly equivalent to relational database tables.
MongoDB is a schema-free (or more accurately, "dynamic schema") database.

Upon being inserted into the database, objects are assigned an object ID (if they do not already have one) in the field _id.


Saving new entry in "myCollection"  collection


>{"name" : "rahul", "salary" : 2000, "age" : 22 });

>{"name" : "saurabh", "salary" : 3000, "age" : 23, "mobile" : 911888812});

>{"age" : 20, "salary" : 500, "name" : "virender"});

>{"age" : 20, "salary" : 600, "name" : "gautam"});


Document Object Id:

ObjectId: A special 12-byte BSON type that has a high probability an ObjectId represent the time of the ObjectID’s creation. MongoDB uses ObjectId values as the default values for _id fields.

_id : A field containing a unique ID, typically a BSON ObjectId. If not specified, this value is automatically assigned upon the creation of a new document. You can think of the _id as the document’s primary key.

Retrieve data from “myCollection” collection

You can retrieve documents from MongoDB using either of the following methods:

  • find()
  • findOne()

The find() method has the following syntax:

db.collection.find( <query>, <projection> )

·        If there is no <query> argument, the find() method selects all documents from a collection.

·        If there is a <query> argument, the find() method selects all documents from a collection that satisfies the criteria of the query.



//prints all documents of a collection


Example 1: The following operation returns all documents in “myCollection” having name=sachin .

> db.myCollection.find( {name:’sachin’} );


Comparison Operator









Logical Operator






Example 2: find all entries where name starts with "r" and age =22.

>db.myCollection.find( { name:/^r/,age:22 } );


Example 3: find all entries where name=rahul or name=sachin.

>db.myCollection.find({name : {$in: ['rahul','sachin']}});


Example 4: find all entries where name contains character "s" or salary >=22.

>db.myCollection.find( { $or :[ { name : /.*s.*/ } , { age : { $gte : 22 } } ] } );

//For multiple AND criteria on the same field, use the $and operator.


Example 5: find name and age of all entries where name has a charater 'b'.

>db.myCollection.find({ name:/.*b.*/ } , { name:1, age:1,  _id : 0 });


Example 6: find all names in collection in sorted order by name in ascending order.

>db.myCollection.find( {} , {name:1, _id:0} ).sort({name:1});



The _id field is implicitly included in the <projection> argument. In projections that explicitly include fields, _id is the only field that you can explicitly exclude. Otherwise, you cannot mix include field and exclude field specifications.


Example 7: find all names in collection in sorted order by age in ascending order and if age is same sort it by name in descending order.

>db.myCollection.find( {} , { name:1,age:1, _id:0 } ).sort( {age :1, name :-1} );


Example 8: find all names having salary greater than 500 in collection in sorted order by age in ascending order and if age is same sort it by name in descending order.

>db.myCollection.find(  { salary : {$gt:500} } , { name : 1 , age : 1, _id : 0 }).sort( {age:1, name:-1} );


For more help:


How to Update a document :

The update() method modifies an existing document or documents in a collection. By default the update() method updates a single document. To update all documents in the collection that match the update query criteria, specify the multi option. To insert a document if no document matches the update query criteria, specify the upsert option.


db.collection.update(query, update, <upsert,> <multi>)

The update() method takes the following parameters:


query (document) – Specifies the selection criteria for the update. The query parameter employs the same query selectors as used in the db.collection.find() method.

update (document) – Specifies the modifications to apply.

If the update parameter contains any update operators expressions such as the $set operator expression, then:

·         the update parameter must contain only update operators expressions.

·         the update method updates only the corresponding fields in the document.

If the update parameter consists only of field: value expressions, then:

·         the update method replaces the document with the updates document. If the updates document is missing the _id field, mongoDB will add the _id field and assign to it a unique objectId .

·         the update method updates cannot update multiple documents.

options : (optional) Specifies whether to perform an upsert and/or a multiple update. Use the options parameter instead of the individual upsert and multi parameters.

upsert : A kind of update that either updates the first document matched in the provided query selector or, if no document matches, inserts a new document having the fields implied by the query selector and the update operation. The default value is false. When true, the update() method will update an existing document that matches the query selection criteria or if no document matches the criteria, insert a new document with the fields and values of the update parameter and if the update included only update operators, the query parameter as well .

multi : (optional) Specifies whether to update multiple documents that meet the query criteria.

When not specified, the default value is false and the update() method updates a single document that meet the query criteria.

When true, the update() method updates all documents that meet the query criteria.


Example9 : change salary = 5000 in collection where name == ‘sachin’ .

>db.myCollection.update(  {name : 'sachin'} , { $set : {salary : 5000}}  );

//This will update the first document having name=sachin. (multi is set to false by default, upsert is set to false by default)


Example 10: change salary=200 for all entries where age=20.

>db.myCollection.update({age:20}, {$set:{salary:200}}, false, true);


Example 11: Add new field “status” having value as “senior” if salary is greater than or equal to 1000.

>db.myCollection.update( {salary : { $gte: 1000 } } , { $set: { 'status' : 'senior' } } , false , true);


Example 12: Add new field  “profile” to all documents as “player”.

>db.myCollection.update( {}, { $set :{ 'profile': 'player' } } , false , true );


Example 13: Drop field “status” from all documents.

> db.myCollection.update( {status: {$exists: true}}, {$unset: {status: 1}}, false, true);


for more info on update go to:

Get number of documents in a collection:



How to delete documents from a collection:


// removes all

>db.mytable.remove({ salary : 1000 });

// removes all where salary == 1000 


How to drop entire collection:



How to delete database: 

//set the database which you want to delete as current database

>use mydb



How to show all databases:

>show dbs


How to show all collections in current database:

>show collections


Showing statistics of collection:



Showing statistics of database:



Here are some screenshots for the above commands:

  • Adding new DB and authenticated user


  • Saving new documents and retrieving data



  • Example2



  • Example3


  • Example4



  • Example5



  • Example6



  • Example7



  • Example8


  • Example9


  • Example10


  • Example11


  • Example12



  • Example13


For some advanced mongoDB quiries I have written a blog Basic queries for CRUD operations in MongoDB II.


Akash Sharma


Request for Proposal

Name is required

Comment is required

Sending message..