Introduction To MongoDB

Ibad Siddiqui
6 min readSep 21, 2018

--

MongoDB Inc.

MongoDB is an open-source database developed by MongoDB Inc. that’s scalable and flexible. MongoDB stores data in JSON-like documents that can vary in structure.

MongoDB is a document-oriented database system. It has a JSON-like document structure that is flexible and easy to work with. Here’s an example of what a MongoDB document looks like:

{
"_id": ObjectId(1234567),
"type": "Article",
"title": "MongoDB Tutorial Part One",
"description": "First document",
"author": "Ibad Siddiqui",
"content": "This is the content"
}
{
"_id": ObjectId(8910111213),
"type": "Article",
"title": "MongoDB Tutorial Part Two",
"description": "Second document",
"author": "Ibad Siddiqui",
"content": "In the second article, we have..."
}

A document in a NoSQL database corresponds to a row in an SQL database. A group of documents together is known as a collection, which is roughly synonymous with a table in a relational database.

A part from being a NoSQL database, MongoDB has a few qualities of its own. I’ve listed some of its key features below:

  • It’s easy to install and set up
  • It uses a BSON (a JSON-like format) to store data
  • It’s easy to map the document objects to your application code
  • It claims to be highly scalable and available, and includes support for out-of-the-box replication
  • It supports MapReduce operations for condensing a large volume of data into useful aggregated results
  • It’s free and open source.

MongoDB appears to overcome the limitations of the age-old relational databases and NoSQL databases.

Let’s go ahead and install MongoDB.

Installing MongoDB:

Installing MongoDB is easy and it doesn’t require much configuration or setup. MongoDB is supported by all major platforms and distributions, and you can check out their documentation if you’re in doubt.

I’ve covered the instructions for installing MongoDB on Windows below. For Linux, MongoDB recommends installing the software with the help of your distribution’s package manager.

Downloading & Installing MongoDB on Windows:

You can download MongoDB (.msi or .exe)using the following link: https://www.mongodb.com/download-center?jmp=nav#community:

MongoDB Download Center.

After installing it, create a data directory so that the mongod process will be able to write data. By default, the directory is C:\data\db:

C:\>mkdir data
C:\>cd data
C:\>mkdir db

Initiate the MongoDB server. Run the mongod command to start the server. Now to start the Mongo shell, open up another terminal window and run: mongo. The mongo shell will attempt to connect to the mongo daemon that we initiated earlier. Once you’re successfully connected, you can use the shell as a playground to safely run all your commands.

Exit the Mongo shell by running quit() and the mongo daemon by pressing control + C.

Now that we have the mongo daemon up and running, let’s get acquainted with the MongoDB basics.

Basic Database Operations:

Enter mongo shell, keep the server running:

C:\Users\IBAD SIDDIQUI>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
>

You can see my version of MongoDB shell. By default, you’re connected to a test database. You can verify the name of the current database by running db:

>db
test
>

That’s awesome, but what if we want a new database? To create a database, MongoDB has a use DATABASE_NAME command:

>use example
switched to db example

To display all the existing databases, try show dbs:

> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB

The example isn’t in the list because we need to insert at least one document into the database. To insert a document, you can do db.COLLECTION_NAME.insertOne({"key":"value"}). Here’s an example:

> db.users.insertOne({'name':'Ibad'})
{
"acknowledged" : true,
"insertedId" : ObjectId("5a52c53b223039ee9c2daaec")
}

MongoDB automatically creates a new users collection and inserts a document with the key-value pair 'name':'Ibad'. The ObjectId returned is the id of document inserted. MongoDB creates a unique ObjectId for each document on creation and it becomes the default value of the _id field:

> show dbs
admin 0.000GB
config 0.000GB
example 0.000GB
local 0.000GB
>

Similarly, you can confirm that the collection was created using the show collections command:

> show collections
user

We’ve created a database, added a collection named user and inserted a document into it. Now let’s try dropping it. To drop an existing database, use the dropDatabase() command as exemplified below:

> db.dropDatabase()
{ "dropped" : "example", "ok" : 1 }

show dbs confirms that the database was indeed dropped.

> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB

MongoDB CRUD Operations:

The CRUD acronym stands for Create, Read, Update, and Delete. These are the four basic database operations that you can’t avoid while building an application. For instance, any modern application will have the ability to create a new user, read the user data, update the user information and, if needed, delete the user account. Let’s accomplish this at the database level using MongoDB.

Create Operation:

Creation is the same as inserting a document into a collection. In the previous section, we had inserted a single document using the db.collection.insertOne() syntax. There’s another method called db.collection.insertMany() that lets you insert multiple documents at once. Here’s the syntax:

> db.COLLECTION_NAME.insertMany(
[ <document 1>; , <document 2>, ... ]
)

Let’s create a users collection and populate it with some actual users:

> db.users.insertMany([
{ "name": "Ibad","age":22, "email": "ibadsiddiqui01@gmail.com" },
{ "name":"Tim", "age":25, "email":"Tim@example.com" },
{ "name": "Shane", "age": 27, "email": "Shane@example.com" },
{ "name": "Lili", "age":15, "email":"lili@example.com"}
])

{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5a52cb2451dd8b08d5a22cf5"),
ObjectId("5a52cb2451dd8b08d5a22cf6"),
ObjectId("5a52cb2451dd8b08d5a22cf7"),
ObjectId("5a52cb2451dd8b08d5a22cf8")
]
}

The insertMany method accepts an array of objects and, in return, we get an array of ObjectIds.

Read Operation:

R ead operation is used to retrieve a document or multiple documents from a collection. The syntax for the read operation is as follows:

> db.[collection_name].find(query, projection)

To retrieve all user documents, you can do this:

> db.users.find().pretty()
{
"_id" : ObjectId("5a52cb2451dd8b08d5a22cf5"),
"name" : "Ibad",
"age" : 22,
"email" : "ibadsiddiqui01@gmail.com"
}
{
"_id" : ObjectId("5a52cb2451dd8b08d5a22cf6"),
"name" : "Tim",
"age" : 25,
"email" : "Tim@example.com"
}
{
"_id" : ObjectId("5a52cb2451dd8b08d5a22cf7"),
"name" : "Shane",
"age" : 27,
"email" : "Shane@example.com"
}
{
"_id" : ObjectId("5a52cb2451dd8b08d5a22cf8"),
"name" : "Lili",
"age" : 15,
"email" : "lili@example.com"
}

This corresponds to the SELECT * FROM USERS query from an SQL database.

The pretty method is a cursor method, and there are many others too. You can chain these methods to modify your query and the documents that are returned by the query.

What if you need to filter queries and return a subset of the collection? Say, find all users who are below 30. You can modify the query like this:

> db.users.find({ "age": { $lt: 25 } })
{ "_id" : ObjectId("5a52cb2451dd8b08d5a22cf5"), "name" : "Ibad", "age" : 22, "email" : "ibadsiddiqui01@gmail.com" }
{ "_id" : ObjectId("5a52cb2451dd8b08d5a22cf8"), "name" : "Lili", "age" : 15, "email" : "lili@example.com" }

$lt is a query filter operator that selects documents whose age field value is less than 25. There are many comparison and logical query filters available, and you see the entire list in the Query Selector documentation.

Update Operation:

The update operation modifies the document in a collection. Similar to the create operation, MongoDB offers two methods for updating a document. They are:

  1. db.collection.updateMany(filter, update, options)
  2. db.collection.updateMany(filter, update, options)

If you need to add an extra field, say registration, to all the existing documents in a collection, you can do something like this:

> db.users.updateMany({}, {$set: { 'registration': 'incomplete'}})
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }

The first argument is an empty object because we want to update all documents in the collection. The $set is an update operator that sets the value of a field with the specified value. You can verify that the extra field was added using db.users.find().

To update the value of documents that match certain criteria, updateMany() accepts a filter object as the first argument. For instance, you might want to overwrite the value of registration to complete for all users who are aged 18+. Here is what you can do:

> db.users.updateMany(
{'age':{ $gt: 18} },
{$set: { 'registration': 'complete'}
})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

To update the registration details of a single user, you can do this:

> db.users.updateOne(
{'email': 'lili@example.com' },
{$set: { 'registration': 'complete'}
})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Delete Operation:

Delete operation removes a document from the collection. To delete a document, you can use the db.collection.deleteOne(filter, options) method, and to delete multiple documents, you can use the db.collection.deleteMany(filter, options) method.

To delete documents based on certain criteria, you can use the filter operators that we used for the read and update operation:

db.users.deleteMany( { status: { $in: ["dormant", "inactive" ]}})

{ "acknowledged" : true, "deletedCount" : 1 }

This deletes all documents with a status of “dormant” or “inactive”.

That’s it.

--

--

Ibad Siddiqui

Software Engineer at @GlaxoSmithKline. Writer @Coinmonks | Blockchain & Data Science Enthusiast | Traveler | Explorer