MongoDB Shell and its Commands

An article about what is MongoDB Shell and what are its commands

MongoDB Shell and its Commands

What is MongoDB Shell ?

MongoDB shell is a CLI(Command Line Tool) which is used to access databases,collections and documents present in MongoDB.

How to access MongoDB shell ?

Before accessing Mongo Shell, first we need to start the Mongod Process.

To start it, we just have to open the terminal and type

sudo systemctl start mongod

Once starting Mongod Process, we are good to open the mongo shell.

To open mongo shell we have to open terminal and type

mongo

That all, now you are in the mongo shell.

Mongo Shell Commands

To see all the databases

show dbs

To create a new database/To switch to any existing database

use Name-Of-Database

To see all the collections of a database

show collections

To create a new collection in a database

db.createCollection(Name-of-new-collection)

To see all the documents of a collection

db.Name-of-Collection.find()

To find a document matching with query

db.Name-of-Collection.find({key:value})

To find the first occurrence of the document

db.Name-of-Collection.findOne({key:value})

To insert a document in collection

db.Name-of-Collection.insert({key:value})

To insert multiple documents in a collection

db.Name-of-Collection.insert( [ {key:value}, {key:value}, {key:value} ....  ] )

To update any document in a collection

db.Name-of-Collection.update({key:value},{key:value});

Here first key value pair is use to find the document and second one is the data to be inserted

There is one thing we have to keep in mind while updating.

If we use above line of code it will simply remove all the data of that particular document and write whatever we passed as key value.

To tackle this problem, we can use $set{ } which will only update the matching key value pair.

db.Name-of-Collection.update( { key:value } , { $set : {key:value} });

To remove all the document from a collection

db.Name-of-Collection.remove( { } )

To remove a specific document from the collection

db.Name-of-Collection.remove( { key:value } );

To delete the whole collection from the database

db.Name-of-Collection.drop( );

To delete the entire database

db.dropDatabase( );

These are some basic Mongo Shell commands.I hope you learn something from it.

Happy Coding