Introduction to MongoDB — Installation, Shell, and Database Management

Waqas Ahmad
6 min readJun 19, 2023

--

Introduction

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 a specific pre-defined schema, fields, constraints, types 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 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:

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

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 leave with a MongoDB shell.

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.

> show dbs
2 local 0.000GB
3>

Create a Database

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

> use organization
2 switched to db organization
3>

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.

> db
2 organization
3>

Documents

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

{
"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:

{
"name": "Muhammad Saim",
"degree": "Cloud Computing",
"email": "saim@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:

{
"name": "Muhammad Saim",
"degree": "Cloud Computing",
"email": "saim@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 of creating users is db.createUser(). There are different ways to do this, but let's focus on the simple one:

db.createUser({
2 user: "saim",
3 pwd: "saim",
4 roles: ["readWrite", "dbAdmin"]
5});

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

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

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

Now that we have a user, let’s proceed to add 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 }
3>

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:

> show collections
2 students
3>

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 > db.students.insert({
2 name: "Muhammad Saim",
3 degree: "Cloud Computing",
4 email: "saim@example.com",
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});

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

1 > db.students.insert({
2... "name": "Muhammad Saim",
3... "degree": "Cloud Computing",
4... "email": "saim@example.com",
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 })
22>

We can see this 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 the collection has been inserted correctly. Use db.collection.find() as follows:

> db.students.find();
2{ "_id" : ObjectId("592ebe7e8e61243307417cc4"), "name" : "Muhammad Saim", "degree" : "Cloud Computing", "email" : "saim@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" ] }
3>

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();
2{
3 "_id" : ObjectId("592ebe7e8e61243307417cc4"),
4 "name" : "Muhammad Saim",
5 "degree" : "Cloud Computing",
6 "email" : "saim@example.com",
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 ]
26}
27>

Ah, now this is what we inserted. It looks better than the 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 an 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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Waqas Ahmad
Waqas Ahmad

Written by Waqas Ahmad

Software Engineering Leader | Consultant Cloud Infra DBA at Systems Limited

No responses yet

Write a response