MongoDB Shell Basics – Insert, Update, Find, Delete and Indexing

MongoDB Shell Basics – Insert, Update, Find, Delete and Indexing


The mongo shell provides an interactive interface written in Javascript to talk directly to MongoDB. Using this shell you can issue many of the administrative commands as well as perform data manipulation and extraction of the data within MongoDB.

Starting the MongoDB Shell (Windows)

To start the mongo shell please ensure you switch to the current installation directory and issue the mongo in the command line.

Please Note
You must ensure that MongoDB is running prior to attempt to connect to it. Failure to do so will result in a error message:

Failed to connect to, reason: errno:10061 No connection could be made because the target machine actively refused it. Error: couldn’t connect to server (, connection attempt failed at src/mongo/shell/mongo.js:146 exception: connect failed

To Start MongoDB as a standalone process, type mongod and hit ENTER. Otherwise refer to the section on Starting MongoDB as a Windows service.

MongoDB Directory Structure (Windows)



Using MongoDB Shell Help

To show the commands available in the MongoDB Shell type in the shell command prompt >. When you do this, it will display a list of commands as shown below.

General Help

MongoDB shell version: 2.6.11
connecting to: test
> help                 help on db methods          help on collection methods                 sharding helpers                 replica set helpers
  help admin                administrative help
  help connect              connecting to a db help
  help keys                 key shortcuts
  help misc                 misc things to know
  help mr                   mapreduce

  show dbs                  show database names
  show collections          show collections in current database
  show users                show users in current database
  show profile              show most recent system.profile entries with time >= 1ms
  show logs                 show the accessible logger names
  show log [name]           prints out the last segment of log in memory
  use <db_name>             set current database             list objects in collection foo { a : 1 } )  list objects in foo where a == 1
  it                        result of the last line evaluated; use to further iterate
  DBQuery.shellBatchSize=x  set default number of items to display on shell
  exit                      quit the mongo shell

Database Specific Help

MongoDB shell version: 2.6.11
connecting to: test
DB methods:
    db.auth(username, password)
    db.commandHelp(name) returns the help for the command
    db.copyDatabase(fromdb, todb, fromhost)
    db.createCollection(name, { size : ..., capped : ..., max : ... } )
    db.currentOp() displays currently executing operations in the db
    db.eval(func, args) run code server-side
    db.fsyncLock() flush data to disk and lock server for backups
    db.fsyncUnlock() unlocks server following a db.fsyncLock()
    db.getCollection(cname) same as db['cname'] or db.cname
    db.getLastError() - just returns the err msg string

Collections Specific Help

MongoDB shell version: 2.6.11
connecting to: test
DBCollection help
    db.avaldes.find().help() - show DBCursor help
    db.avaldes.distinct( key )
    db.avaldes.drop() drop the collection

Methods Specific Help

MongoDB shell version: 2.6.11
connecting to: test
> db.avaldes.find().help()
find() modifiers
    .sort( {...} )
    .limit( n )
    .skip( n )
    .count(applySkipLimit) - total # of objects matching query
    .size() - total # of objects cursor would return, honors skip,limit
    .addOption(n) - adds op_query options -- see wire protocol


Creating a new Database or Using an Existing MongoDB Database

If you want to use an existing database or create a new database issue the use command. Please note that MongoDB will not actually create a NEW database until you have inserted at least one document into it.

MongoDB shell version: 2.6.11
connecting to: test
> use avaldes
switched to db avaldes

Show list of Available Databases

Please Note
Even though you have switched to the new database avaldes, it has NOT been created as no data has been inserted into it. MongoDB will NOT physically create the database until data has been stored in it.
> show dbs
admin   0.078GB
test    0.078GB

Displaying the current Database in MongoDB Shell

To display the current database you are using, type db:

> db

Creating a new Database, Collection(Table), Inserting a Document(Record) and displaying the results(Find)

Once we store data into the new database avaldes it will show up in the list of databases when using show dbs command. Additionally, MongoDB will also create the collection called employee and insert the first document containing the fields: first_name, last_name, pay_rate, and active.

> db.employee.insert({"first_name":"John", "last_name":"Smith", 
"pay_rate":57000, "active":1})
WriteResult({ "nInserted" : 1 })
> db.employee.find()
{ "_id" : ObjectId("54fe4b8fa74916e71d225484"), "first_name" : "John", 
"last_name" : "Smith", "pay_rate" : 57000, "active" : 1 }

Displaying Formatted Results using Pretty

To format the printed result, you can add the .pretty() to the find() operation, as in the following:

> db
> db.employee.find().pretty()
  "_id" : ObjectId("54fe4b8fa74916e71d225484"),
  "first_name" : "John",
  "last_name" : "Smith",
  "pay_rate" : 57000,
  "active" : 1

Using Find in MongoDB


To output all of the documents in the ’employee’ collection.

> db.employee.find()

To output all of the documents in the employee collection, whose first_name=’John’.

> db.employee.find({"first_name":"John"})

{ "_id" : ObjectId("54fe4b8fa74916e71d225484"), "first_name" : "John", 
"last_name" : "Smith", "pay_rate" : 57000, "active" : 1 }
{ "_id" : ObjectId("54fe4c7f636abc955c777dfc"), "first_name" : "John", 
"last_name" : "Holden", "pay_rate" : 94500, "active" : 1 }
{ "_id" : ObjectId("54fe4dab636abc955c777dff"), "first_name" : "John", 
"last_name" : "Fitzgerald", "pay_rate" : 79750, "active" : 1 }
{ "_id" : ObjectId("54fe4ea6636abc955c777e00"), "first_name" : "John", 
"last_name" : "Henry", "pay_rate" : 43850, "active" : 1 }

Using Projection in Find to Limit the Fields being returned

To output all of the documents in the employee collection, whose first_name=’John’, but only showing _id, first_name, last_name fields.

> db.employee.find({"first_name":"John"}, {first_name:1,last_name:1})

{ "_id" : ObjectId("54fe4b8fa74916e71d225484"), "first_name" : "John", 
"last_name" : "Smith" }
{ "_id" : ObjectId("54fe4c7f636abc955c777dfc"), "first_name" : "John", 
"last_name" : "Holden" }
{ "_id" : ObjectId("54fe4dab636abc955c777dff"), "first_name" : "John", 
"last_name" : "Fitzgerald" }
{ "_id" : ObjectId("54fe4ea6636abc955c777e00"), "first_name" : "John", 
"last_name" : "Henry" }

To output all of the documents in the employee collection, whose first_name=’John’, but only showing first_name, last_name fields. Notice how we added _id:0 to ensure we exclude the _id from result set.

> db.employee.find({"first_name":"John"}, {_id:0,first_name:1,last_name:1})

{ "first_name" : "John", "last_name" : "Smith" }
{ "first_name" : "John", "last_name" : "Holden" }
{ "first_name" : "John", "last_name" : "Fitzgerald" }
{ "first_name" : "John", "last_name" : "Henry" }

To output all of the documents in the employee collection, whose first_name=’John’, but only showing first_name, last_name and pay_rate fields.

> db.employee.find({"first_name":"John"}, 

{ "first_name" : "John", "last_name" : "Smith", "pay_rate" : 57000 }
{ "first_name" : "John", "last_name" : "Holden", "pay_rate" : 94500 }
{ "first_name" : "John", "last_name" : "Fitzgerald", "pay_rate" : 79750 }
{ "first_name" : "John", "last_name" : "Henry", "pay_rate" : 43850 }

To output all of the documents in the employee collection, whose first_name=’John’ and pay_rate >= 50000, but only showing first_name, last_name and pay_rate fields.

> db.employee.find({"first_name":"John","pay_rate":{$gte:50000}}, 
{ "first_name" : "John", "last_name" : "Smith", "pay_rate" : 57000 }
{ "first_name" : "John", "last_name" : "Holden", "pay_rate" : 94500 }
{ "first_name" : "John", "last_name" : "Fitzgerald", "pay_rate" : 79750 }

Update Documents in MongoDB

Mongo provides a convenient method to perform updates. The update() method allows us to modify data in an existing document.


The following will update ’employee’ collection with last_name=’Fitzgerald’ and update their pay_rate to 85750.

> db.employee.find({"last_name":"Fitzgerald"})
{ "_id" : ObjectId("54fe4dab636abc955c777dff"), "first_name" : "John", "last_name" : "Fitzgerald", "pay_rate" : 79750, "active" : 1 }
> db.employee.update({"last_name":"Fitzgerald"}, {$set:{pay_rate: 85750}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.employee.find({"last_name":"Fitzgerald"})
{ "_id" : ObjectId("54fe4dab636abc955c777dff"), "first_name" : "John", "last_name" : "Fitzgerald", "pay_rate" : 85750, "active" : 1 }
> )

Delete Documents in MongoDB

In order to delete documents from a collection in MongoDB use the remove() method.


To remove all documents from the ’employee’ collection.

> db.employee.remove({})
The recommended method for removing all documents from a collection is to use the drop() method which will remove all indexes as well.

The following will remove the first document that meets this criteria, in this case, whose last_name=’Fitzgerald’.

> db.employee.remove({last_name:"Fitzgerald"})
WriteResult({ "nRemoved" : 1 })

Create Index in MongoDB

db.COLLECTION.ensureIndex({FIELD: 1})

The following will create an index on last_name field in ascending order. If for example, you wanted to create an index in descending order you would specify it as {last_name: -1}

> db.employee.ensureIndex({last_name:1})

To show all indexes available for the employee collection.

> db.employee.getIndexes()
    "v" : 1,
    "key" : {"_id": 1},
    "name" : "_id_",
    "ns" : "avaldes.employee"
    "v" : 1,
    "key" : {"last_name": 1},
    "name" : "last_name_1",
    "ns" : "avaldes.employee"

Exiting the MongoDB Shell

To exit the shell, you can type any of the following:

  1. exit
  2. quit()
  3. ^C use the Ctrl-C keyboard shortcut

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!


Related Posts

Please Share Us on Social Media


Leave a Reply

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