Mongo Shell Commands

  • Mongo shell is a fully functioning JavaScript interpreter, which means that you can create things like JavaScript functions and variables in it.

  • Once mongo shell is installed, we can use the following commands when we dont have a GUI to interact with mongodb.

Common commands

  1. Show databases

show dbs

  1. Select database.

use <database_name> //no angular brackets

  • The above command can be used to view the available namespaces.

  1. To view collections in the database once a database is selected using above command.

show collections

  1. Admin database consists of all the information about users.

  2. Find Command - To query the collections.

    • Returns a cursor, basically a pointer to the query result.

      • To find all documents in a collection

        db.<collection_name>.find({}) OR db.<collection_name>.find()

        • The above command returns at max 20 entries. We can request more by (typing it).

      • To find documents based on criteria

        db.<collection_name>.find({"key": value}) db.<collection_name>.find({"key": value, "key":value })

      • To count the documents in the returned collection

        db.<collection_name>.find({"key":value }).count()

      • To pretty print the result of find query

        db.<collection_name>.find({"key":value }).pretty()

      • To find one document, this one document can be any random document in the collection.

        db.<collection_name>.findOne()

    • Projections in find query

      db.<collection_name>.find({<query>}, {<projections>})

      • Example

         db.account.find(
               { "name": "Joe" },
               { "age": 1, "address": 0, "_id": 0 }
            )
      • In the above example, age is projected and address is not projected in the result.

        • 1 -> include the field

        • 0 -> exclude the field

      • Use only 1s or 0s donot mix and match, exception being _id field which is always projected, if not explicitly mentioned to be excluded.

  3. Insert Command - To insert document/s in to a collection

    • To insert one document

      db.<collection_name>.insert()

      • Example

         db.accounts.insert({
               "_id":ObjectId("61d982f17d3abc1d237445b3"),
               "name" : "John Doe",
               "age":25
         })
      - In the above example "_id" field is specified which needs to be unique in the accounts collection, if not specified mongodb will automatically generate one.
    • To insert many documents at once

      db.<collection_name>.insert([<document1>, <document2> ...])

      • Example

         db.accounts.insert([
         {
               "_id":ObjectId("61d982f17d3abc1d237445b3"),
               "name" : "John Doe",
               "age":25
         },
         {
               "_id":ObjectId("61d982f17d3abc1d237445b4"),
               "name" : "Kirsten Smith",
               "age":26
         } 
         ])
      • When inserting duplicate documents, insertion fails on occurence of first duplicate document, hence preventing insertion of remaining valid (non-duplicating) entries. This can be prevented by using "ordered" flag as follows,

          db.accounts.insert([
         {
               "_id":ObjectId("61d982f17d3abc1d237445b3"),
               "name" : "John Doe",
               "age":25
         },
         {
               "_id":ObjectId("61d982f17d3abc1d237445b4"),
               "name" : "Kirsten Smith",
               "age":26
         } ], 
         **{ 
            "ordered":false
         }**
         )
      • Setting ordered flag as false makes documents insertion into collection in unordered manner. This helps when inserting duplicate documents with same "_id" value, so that failure will occur only for duplicate documents and insertion for non duplicate documents will be successful.

  4. Update Command - To update document/s in a collection

    • To update one document.

    db.<collection_name>.update({<restriction>}, {<update operation>})

    • Example

    db.accounts.update(
       {
          "name": "Joe"
       },
       {
          "$set":{
             "name": "Jason"
          }
       }
    )
    • To update many document.

    db.<collection_name>.updateMany({<restriction>}, {<update operation>})

    • Example

    db.accounts.updateMany(
       {
          "age": 17
       },
       {
          "$inc":{
             "age": 1
          }
       }
    )
    • The above update operators i.e., $set and $inc can take more than one fields to update.

    • To add an element to an existing array in document use $push opeerator.

    • Read more about update operators.

  5. Delete Command - To delete document/s from a collection

    • To delete one document

    db.<collection_name>.deleteOne({<restriction>})

    • Example

      db.accounts.deleteOne({"name": "Joe"})
    • To delete many document

    db.<collection_name>.deleteMany({<restriction>})

    • Example

       db.accounts.deleteMany({"name": "Joe"})
  6. Drop Collection

    db.<collection_name>.drop()

  7. db

  • This command prints the current db selected.

Last updated