MongoDB Commands Cheat Sheet

MongoDB Commands Cheat Sheet

Last updated on 14th Oct 2020, Artciles, Blog

About author

Bibin ((Lead Data Engineer ) )

He is a TOP-Rated Domain Expert with 11+ Years Of Experience, Also He is a Respective Technical Recruiter for Past 5 Years & Share's this Informative Articles For Freshers

(5.0) | 11547 Ratings 2122

In this article, you will learn about MongoDB commands, which could get you started and perform minimum database related activities such as create, update, and drop a collection (table). These commands are ideally meant for MongoDB beginners and could be taken as a cheat sheet. You may want to bookmark this page for quick reference.

MongoDB-Logo

If you are mongoDB admin you are interested to get some infomation regarding admin things in one place. I tried to collect few of the admin command and syntax in one place , you know all the syntax and command name is very difficult to collect in one place becuase requirment set for all the admin are different. This page is about the cheat sheet of mongoDB for mongoDB Admin pespective. A mongoDB admin use to do some job or activities in his/her life on day-to-day basis. In the day-to-day life usually few of the commands not remember on that particular time few may remember. For a mongoDB Admin the important is knowledge, I think not important of remembering of syntax and command. Help for syntax and command can be pull from different sources like google, notes.

Subscribe For Free Demo

Error: Contact form not found.

Why MongoDB Commands?

  1. 1. It can easily control the data which is placed globally, ensuring fast performance and compliance.
  2. 2. It provides a flexible data model. This goes with the case, where the app needs to be built from scratch or the case of updating a single record.
  3. 3. No downtime, if the application is scaled.

Features

  1. 1. MongoDB command uses a master-slave replication concept. To prevent database downtime, this replica feature is proved to be a very important feature.
  2. 2. This database can run over multiple servers; hence data is duplicated over multiple servers. The result of which it’s a great advantage in case of hardware failure.
  3. 3. MongoDB command comes with the auto-sharding feature, in which process distributes data across multiple physical partitions known as shards. The result of which automatic load balancing happens.
  4. 4. It’s schema-less. Hence more efficient.

Basic of MongoDB Commands

1. Create Database

In MongoDB use, DATABASE_NAME is used to create a database. If this name database doesn’t exist, it will get created, else it will return the existed one.

Create-Database

To check the current database now:

Create-Database

By default, MongoDB command comes with database name “test”. Suppose you inserted a document without specifying the database, it will automatically be stored in “test” database.

2. Drop Database

 Drop-Database

If the database is not specified, then it will delete the default database that is “test”.

3. Create Collection

To create collection, the MongoDB command used is: db.createCollection(name, options)

Here, the name is the name of the collection & options is a document that is used to specify the configuration of the collection. Though “Options” parameter is optional, it’s good to provide it.

4. Drop Collection

Drop-Collection
Drop-Collection

5. Insert Document

Insert() or save() method is used to insert data into a collection of any database.

 Insert-Document

Here “mycol” is the collection name. If the collection doesn’t exist, then MongoDB command will create the collection in the database and then it will get inserted.

6. Query Document

Querying collection is done by find() method.

As find() method will show the findings in a non-structured way, to get the results in a structured pretty() method is used.

Query-Document

Intermediate MongoDB Commands

1. Limit()

This MongoDB command limits the no. of records need to use in MongoDB. The argument of this function accepts only number type. The argument is the number of the document that needs to be displayed.

Limit()

2. Sort()

This is to the records of MongoDB. 1 & -1 are used to sort the documents. 1 is for ascending whereas -1 is for descending.

Sort

3. Indexing is the concept that helps MongoDB to scan documents inefficient way

Indexing

Advanced Commands of  MongoDB

1. Aggregate ()

This MongoDB command helps in processing the data, which returns the calculated result. This can group values from multiple documents together.

Aggregate

2. Replication

Replication in MongoDB is achieved using replication set. A replica set is a group of mongoDB processes that have the same dataset. Replica set provides:

  1. 1. High availability
  2. 2. Redundancy hence faults tolerant/disaster recovery.

In replica, one node is the primary node and rest others are the secondary node. All write operations remains with the primary node.

Let’s see, standalone MongoDB instance gets converted into a replica set.

Here are steps for that:

Close already running MongoDB server.

Now Start the MongoDB server by specifying — replSet option.

Syntax:

Syntax

3. Create & restore Backup

To create the backup, mongodump command is used. Entire data of the server will be dumped into a dump directory(/bin/dump/). Options are there to limit the data.

Create-Restore

To restore the backup, a mongorestore command is used.

Create-Restore-Backup

4. Monitor Deployment

To check the status of all your running processes/instances, a mongostat command is helpful. It tracks and returns the counter of database operations. These counters include inserts, updates, queries, deletes, and cursors. This MongoDB command is beneficial as it shows your status about low running memory, some performance issues, etc.

You need to go to your bin directory of MongoDB installation and run mongostat.

Monitor-Deployment

MongoDB Commands Cheat Sheet

The following is the list of the commands:

Start and stop the MongoDB Database:

  • sudo service mongod start
  • sudo service mongod stop

Access the MongoDB database using Shell:

  • mongo –host localhost:27017

Show all databases:

  • show dbs

Create a database, 

  • say, testdb; 

Switch to the database:

  • use testdb

Until a collection is created in a database, the database name is not listed as a result of execution of the command, 

  • show dbs

Add a collection:

  • db.createCollection(“user”)

Show all collections in a database; Execute the “use dbname” command to access the database before executing the command given below.

  • show collections
  • show tables

The following command also work:

  • db.getCollectionNames()

Insert a record in the collection: A record is inserted in the collection, “user.”

  • db.user.insert({“name”: “Ajitesh Shukla”, “location”: “hyderabad”, “username”: “ajitesh”})

Display list of records of a collection:”user” collection is used.

  • db.user.find()
  • db.user.find().pretty()

Display a list of records matching with value (s) of specific fields:

  • db.user.find({“username”: “ajitesh”})
  • db.user.find({“username”: “ajitesh”, “location”: “hyderabad”})

Drop the collection:

  • db.user.drop()

Create users in the database:

The below command creates a user with username as “ajitesh” and having the role such as “readWrite” and “dbAdmin”

  • db.createUser({“user”: “ajitesh”, “pwd”: “gurukul”, “roles”: [“readWrite”, “dbAdmin”]})

Show users; If executed without selecting a database, it displays all users along with database information.

show users

Login into the database with username and password:

  • mongo -u USERNAME -p PASSWORD –authenticationDatabase DATABASENAME

For user created in above command, the login command would look like the following:

  • mongo -u ajitesh -p gurukul –authenticationDatabase testdb

Tips and Tricks to use MongoDB commands

  • Pre-allocate space: When you know, your document is going to grow up to a certain size. This is an optimization technique in MongoDB. Insert a document and add garbage field.
  • Try fetching data in a single query
  • As MongoDB is by default case sensitive.
MongoDB Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Example:

  • db.people.find({name: ‘Russell’}) &
  • db.people.find({name: ‘russell’}) are different.

While performing a search, its good habit to use regex. Like:

  • db.people.find({name: /russell/i})
  • Prefer Odd No. of Replica Sets: An easy way to add redundancy and increase read performance is by using replica sets. Data is replicated between all nodes, and in case of primary node failure. Voting takes place between themselves, and the primary node is elected. Using the odd number of replica will make voting easier in case of failure.
  • Secure MongoDB by using a firewall: As MongoDB itself doesn’t provide any authentication, it’s better to secure it with firewall and mapping it to correct interface.
  • No joins: As we know, joins are not supported by MongoDB. To retrieve data from more than two collections, one needs to write more than one query. And if the schema is not well organized, writing query may go hectic. This may result in the re-designing of the schema. It’s always better to spend some extra time to design a schema.

 Conclusion

MongoDB commands is the best practice solution to maintain high availability, efficient and scalable operations, which is as per business demand today.

Are you looking training with Right Jobs?

Contact Us

Popular Courses