Author avatar

Praveen Kumar

Introduction to MongoDB - Installation, Shell, and Database Management

Praveen Kumar

  • Jan 10, 2019
  • 11 Min read
  • Jan 10, 2019
  • 11 Min read


Recently I had to start using MongoDB for an enterprise project and I learned a lot on the way. In this article, I will introduce MongoDB and how to get started with using it. By the end of this series of guides, you will understand everything up to the basic CRUD (Create, Retrieve, Update, Delete) operations.

MongoDB is a NoSQL database framework. NoSQL Databases are different from traditional Relational Databases (RDBs) like MySQL or postgreSQL. RDBs have specific pre-defined schema, fields, constraints, type of fields, triggers, and so on.

In the case of a typical NoSQL Database, there's nothing like the above. There's no need to define a structure before building the database. This allows a MongoDB database to scale up or down depending on the application, whereas the traditional RDBs do not scale easily. NoSQL is much faster in most cases; so if you need to store or retrieve large quantities of data, NoSQL is the way to go.

There are different types of NoSQL databases, such as key-value stores, document databases, wide-column stores, and graph databases. MongoDB, a Document Database, stores all schema and records in documents using a syntax like JSON (JavaScript Object Notation). If you are familiar with Web Development, MongoDB will seem comfortable.


Please refer to the official MongoDB guides to install the database essentials.

Once you have installed MongoDB, add the bin directory to the path. You need to be aware of two binary executable files.

  • mongod - This is the daemon (a program that always runs in the background as a service) for MongoDB Server.
  • mongo - This is the command line client shell interface for MongoDB.

Note: The MongoDB server usually runs in the port 27017.


The shell is started by executing the mongo command from any of your operating system command line terminal interfaces:

1C:\Users\Praveen> mongo⏎                  #     Windows
2Praveen-MBP:~ Praveen$ mongo⏎             #   Macintosh
3praveen@ubuntu:~$ mongo⏎                  #      Ubuntu

Once you get into this part, you should see a black screen with the following:

1praveen@ubuntu:~$ mongo
2MongoDB shell version: 3.0.7
3connecting to: test
4Server has startup warnings:
5[ some crazy error info messages ]
6[ you don't need to worry about  ]

There will be a few crazy warnings, which you need not worry about. If we press Ctrl + L or type cls in the shell and hit Enter, all the messages will be cleared. And you will be left with the MongoDB Shell:



Show all the Databases

To list all the databases available in the current server, we need to use the command show dbs. It shows the one default local database and we’ll leave it aside without touching it.

1> show dbs
2local      0.000GB

Create a Database

To create and use a new database we need the use command. Let's create a new database named praveen:

1> use praveen
2switched to db praveen

When we use the use command, it creates a new database, if one doesn't already exist, and also switches to that database.

To check the current database we are in, we have a handy command called db to the rescue. When in doubt, it will give us the current database we are in.

1> db


The syntax of a document looks like JSON (JavaScript Object Notation). For example:

2  "field1": "value1",
3  "field2": "value2",
4    // --- and so on ---
5  "fieldN": "valueN"

Note: A valid JSON will not have a trailing comma. Look at the last value- ValueN doesn't end with a comma.

Let's consider a student record. A typical student record might contain basic details like name, email, and degree:

2  "name": "Praveen Kumar",
3  "degree": "Cloud Computing",
4  "email": "[email protected]"

The above set of data is just simple string values. Arrays and objects can also be values in our database. For example, our database might have a field for subjects, which keeps track of all classes in array format. In this example, each class or course would be an object that represents a subject's details. We could also keep students' phone numbers in array format. Each of these usages is shown below:

2  "name": "Praveen Kumar",
3  "degree": "Cloud Computing",
4  "email": "[email protected]",
5  "subjects": [
6    {
7      "name": "Internet Networks",
8      "prof": "Prof. Awesome Blossom"
9    },
10    {
11      "name": "Cloud Computing",
12      "prof": "Prof. Tech Ninja"
13    },
14    {
15      "name": "Web Development",
16      "prof": "Prof. Chunky Monkey"
17    }
18  ],
19  "phone": ["9840035007", "9967728336", "7772844242"]

Database Management

User Management

To start using our freshly-brewed MongoDB Database, we need to create some users. The function for creating users is db.createUser(). There are different ways to do this, but let's focus on the simple one:

2  user: "praveen",
3  pwd: "praveen",
4  roles: ["readWrite", "dbAdmin"]

Note: The db variable here denotes the current active database.

Doing this operation on the shell will give you a success output similar to the following:

1> db.createUser(
2...   {
3...     user: "praveen",
4...     pwd: "praveen",
5...     roles: [ "readWrite", "dbAdmin" ]
6...   }
7... )
8Successfully added user: { "user" : "praveen", "roles" : [ "readWrite", "dbAdmin" ] }

Now that we have a user, let's proceed to adding some data!

Content Management

In traditional databases, we generally use schema (or tables), but there's no such hard and fast rule for NoSQL Databases. We have Collections instead of Tables. Basically, collections hold the documents or records.

Creating Collections

To create a collection, use the db.createCollection() method. It takes one parameter: the name of the collection. To create a collection for students, we'll use:

1> db.createCollection("students");
2{ "ok" : 1 }

The success message will be ok with the count of affected items (or created collections, in this case).

Listing Collections

To list out all the collections in this particular database we can use show collections. The output will be similar to:

1> show collections

Inserting into Collections

Inserting into collections is similar to an array's push function. We'll use the db.collection.insert() function. In our case, the collection is students. So, we'll use:

2  name: "Praveen Kumar",
3  degree: "Cloud Computing",
4  email: "[email protected]",
5  subjects: [
6    {
7      name: "Internet Networks",
8      prof: "Prof. Awesome Blossom"
9    },
10    {
11      name: "Cloud Computing",
12      prof: "Prof. Tech Ninja"
13    },
14    {
15      name: "Web Development",
16      prof: "Prof. Chunky Monkey"
17    }
18  ],
19  phone: ["9840035007", "9967728336", "7772844242"]

The success message will be similar to what you see here:

1> db.students.insert({
2...   "name": "Praveen Kumar",
3...   "degree": "Cloud Computing",
4...   "email": "[email protected]",
5...   "subjects": [
6...     {
7...       "name": "Internet Networks",
8...       "prof": "Prof. Awesome Blossom"
9...     },
10...     {
11...       "name": "Cloud Computing",
12...       "prof": "Prof. Tech Ninja"
13...     },
14...     {
15...       "name": "Web Development",
16...       "prof": "Prof. Chunky Monkey"
17...     }
18...   ],
19...   "phone": ["9840035007", "9967728336", "7772844242"]
20... });
21WriteResult({ "nInserted" : 1 })

We can see in the result. It shows how many inserts have been done by showing nInserted value as 1.

Listing Collection Items or Documents (Records)

We can use the find() function to see if collection has been inserted correctly. Use db.collection.find() as follows:

1> db.students.find();
2{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Praveen Kumar", "degree" : "Cloud Computing", "email" : "[email protected]", "subjects" : [ { "name" : "Internet Networks", "prof" : "Prof. Awesome Blossom" }, { "name" : "Cloud Computing", "prof" : "Prof. Tech Ninja" }, { "name" : "Web Development", "prof" : "Prof. Chunky Monkey" } ], "phone" : [ "9840035007", "9967728336", "7772844242" ] }

Clearly, our find operation has very complicated output. To the newbie reader, it makes no sense. Let's try to format it using the pretty() function, which goes like:

1> db.students.find().pretty();
3    "_id" : ObjectId("592ebe7e8e61243307417cc4"),
4    "name" : "Praveen Kumar",
5    "degree" : "Cloud Computing",
6    "email" : "[email protected]",
7    "subjects" : [
8        {
9            "name" : "Internet Networks",
10            "prof" : "Prof. Awesome Blossom"
11        },
12        {
13            "name" : "Cloud Computing",
14            "prof" : "Prof. Tech Ninja"
15        },
16        {
17            "name" : "Web Development",
18            "prof" : "Prof. Chunky Monkey"
19        }
20    ],
21    "phone" : [
22        "9840035007",
23        "9967728336",
24        "7772844242"
25    ]

Ah, now this is what we inserted. It looks better than previous machine output. All that we need to do is add .pretty() at the end of any result to make it look pretty.

Wait a minute! Something's new!

We see that there's a new field called _id in the list of fields. We did not add it; MongoDB has a way of identifying records using _id and setting it to an Object with some crazily random value. This is used as a unique value to identify a single record. Please note that this field is automatically created by MongoDB. We don't need to worry about creating the field separately and making it auto-increment and function as the primary key. These are all requirements in a RDB that are made obsolete in a NoSQL database.

Additional Reading

Please continue on to the next guide in this series for more information on MongoDB - Records and Values.