Pluralsight Logo
Author avatar

Praveen Kumar

Author badge Author

Introduction to MongoDB - Installation, Shell, and Database Management

Praveen Kumar

Author BadgeAuthor
  • Aug 7, 2018
  • 11 Min read
  • 6,622 Views
  • Aug 7, 2018
  • 11 Min read
  • 6,622 Views
SQL
MongoDB
NoSQL

Introduction

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.

Installation

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.

Shell

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

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

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

1
2
3
4
5
6
7
praveen@ubuntu:~$ mongo
MongoDB shell version: 3.0.7
connecting to: test
Server has startup warnings:
[ some crazy error info messages ]
[ 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:

1
>

Commands

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
2
3
> show dbs
local      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
2
3
> use praveen
switched 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
2
3
> db
praveen
>

Documents

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

1
2
3
4
5
6
{
  "field1": "value1",
  "field2": "value2",
    // --- and so on ---
  "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:

1
2
3
4
5
{
  "name": "Praveen Kumar",
  "degree": "Cloud Computing",
  "email": "praveen@example.com"
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
  "name": "Praveen Kumar",
  "degree": "Cloud Computing",
  "email": "praveen@example.com",
  "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"]
}

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:

1
2
3
4
5
db.createUser({
  user: "praveen",
  pwd: "praveen",
  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
2
3
4
5
6
7
8
9
> db.createUser(
...   {
...     user: "praveen",
...     pwd: "praveen",
...     roles: [ "readWrite", "dbAdmin" ]
...   }
... )
Successfully 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
2
3
> db.createCollection("students");
{ "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
2
3
> show collections
students
>

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
db.students.insert({
  name: "Praveen Kumar",
  degree: "Cloud Computing",
  email: "praveen@example.com",
  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"]
});

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
> db.students.insert({
...   "name": "Praveen Kumar",
...   "degree": "Cloud Computing",
...   "email": "praveen@example.com",
...   "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"]
... });
WriteResult({ "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
2
3
> db.students.find();
{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Praveen Kumar", "degree" : "Cloud Computing", "email" : "praveen@example.com", "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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
> db.students.find().pretty();
{
    "_id" : ObjectId("592ebe7e8e61243307417cc4"),
    "name" : "Praveen Kumar",
    "degree" : "Cloud Computing",
    "email" : "praveen@example.com",
    "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"
    ]
}
>

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.

16