MongoDB Tutorial: The Ultimate Guide (2023)

by Solomon Eseme

.

Updated Sun Jun 18 2023

MongoDB Tutorial: The Ultimate Guide (2023)

This is the most comprehensive MongoDB tutorial online.

If you’re just starting out with the different stacks such as MEVN, MEAN, etc, and MongoDB is required as the database of choice or you need to learn it quickly and easily:

This MongoDB tutorial does exactly that.

In this MongoDB tutorial, I will explore everything you need to know about MongoDB, from history to installation to creating your first collections and retrieving your documents.

I will explain vividly the concept of Document Oriented Database (DOD) first before diving into MongoDB in as much as this a MongoDB tutorial.

Before we delve in, if you’re a backend developer or looking at delving into this career path, join other developers to receive daily articles on backend development that will boost your productivity.

With websites taking a paradigm shift towards using JSON as the most popular data exchange format over the internet.

This gave rise to numerous No-SQL or Document Oriented Databases like MongoDB.

Before we discuss MongoDB in this tutorial, let’s clarify the concept of Document Oriented Databases and No-SQL.

DOD vs No-SQL

A No-SQL (originally referring to (“non-SQL” or “non-relational”) database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases (Wikipedia).

The data structure used by No-SQL databases includes:

  1. Key-value
  2. Wide-column 
  3. Graph
  4. Document

Which makes it different from relational databases and faster than it too.

Types of No-SQL

We have many types of No-SQL databases but we will only discuss one popular type called Document Store or Document Oriented Database but you can read more here.

What is Document Oriented Database (DOD)

A document-oriented database is a subset of No-SQL and also a subclass of the Key-Value Store data structure we mentioned above.

The main idea behind DOD is the concept of a Document.

It is designed for storing, retrieving, and managing document-oriented or semi-structured data.

While we have different types of DOD with different implementations, in general, they all encode data in some standard formats such as:

  1. XML
  2. JSON
  3. YAML
  4. BSON
  5. PDF
  6. MSWORD
  7. EXCEL
  8. etc

There is no doubt that JSON is the most popular data exchange format over the web, this and many other features make MongoDB a very popular DOD classified as No-SQL.

Introduction to MongoDB

MongoDB is a type of Document Oriented Database that stores the data in the form of JSON/BSON documents. MongoDB is cross-platform and is classified as a No-SQL database program.

It’s very popular among the JavaScript Community with the advent of many stacks such as MEAN, MERN, GERMAN, MEVN where the M equals MongoDB.

Installing MongoDB

MongoDB is available on many different operating systems depending on your development environment.

The different operating systems have listed on the MongoDB website and also links to download and install them.

The installation process for installing the MongoDB community server (free to use for the community of developers ) differs for every operating system, but don’t worry, we will go through each of them one after the other.

If you enjoy watching videos, MongoDB – The Complete Developer’s Guide 2021 is the best MongoDB course out there to learn and master MongoDB in 2021.

Installing in windows

In the MongoDB download center, there is an executable .msi package for installing MongoDB in windows.

Steps

You can install MongoDB by following these steps.

  1. Download the .msi file from here.
  2. Run the MongoDB installer file that was downloaded.
  3. Follow the MongoDB community edition installation wizard.
    1. Choose your setup type (complete)
    2. Service Configuration: Choose either a service that will make MongoDB run automatically or just regular MongoDB installation. If you choose MongoDB as a service! Select the default Network service user which is just a windows user account that is built-in to Windows (read more here). I personally recommend you run MongoDB as a service.
    3. For Windows 8 or greater, you can have the wizard install MongoDB compass. it’s selected by default.
    4. When ready, Click Install
To Start using MongoDB

Open the command prompt with admin privileges and type the following.

 C:\\program Files\mongodb\server\4.4\bin\mongo.exe

Installing In Linux

MongoDB provides many packages to download MongoDB for popular Linux distributions listed here.

To install in Ubuntu 18.04, follow the following guidelines:

  • Import Public key for package mgt. system
  • Create a list file for MongoDB
  • if you are using an older version, check your command here
  • Reload local packages database
  • Install the MongoDB package.
  • Start the service, run:
sudo systemctl start mongod
  • To verify, click the log file for connection messages.
  • Stop the Service, run:
sudo systemctl stop mongod
  • Restart the service, run:
sudo systemctl restart mongod
  • To begin using MongoDB
mongo

Some important directories to note:

  1. Data Directory => /var/lib/mongodb
  2. Log Directory  => /var/log/mongodb
  3. Config File => /etc/mongod.conf

Note: By default, MongoDB runs using the MongoDB user account, if you can the user, you must specify permission for both the log and data directories.

Installing in MacOS

To install MongoDB in macOS, you will need to have Homebrew installed.

After installing brew, follow the below step to install MongoDB:

brew tap mongo/brew

From the terminal, run the following command:

brew install [email protected]

To start MongoDB from the terminal, run this command:

brew services start [email protected]

Some of the important files are here:

  1. Configuration file => /usr/local/etc/mongod.conf
  2. Log Directory => /usr/local/var/log/mongodb/
  3. Data Directory => /usr/local/var/mongodb

To run MongoDB, from the terminal, run:

mongod --config /usr/local/etc/mongod.conf --fork

To connect and start using MongoDB, run:

mongo

If you encounter any issues, read through the docs here.

So there you have it guys, you have successfully installed the latest version of the MongoDB Community edition server in your OS of choice.

Next, let’s get down to business 🙂

Getting Started with MongoDB

After installing the latest version of the MongoDB client in your OS of choice.

Type in this command in your terminal and follow along:

mongo

We will discuss these topics in this MongoDB tutorial:

  1. Databases
  2. Collections
  3. Documents
  4. ObjectID
  5. Cursor

Before you continue with the tutorial, if you enjoy watching videos, MongoDB – The Complete Developer’s Guide 2021 is the best course out there to learn and master MongoDB in 2021.

Databases

A physical container for collections. Each database gets its own set of files on the files system.

A single MongoDB typically has multiple databases.

Database in MongoDB is equivalent to databases in relational databases except that the data are stored in BSON format data rather than a traditional relational database with relationships and different constraints.

A little comparison of the terms used in each type of databases to give you an overview of how different they are:

MongoDB Tutorial: The Ultimate Guide (2021)

In other to switch between databases or use a particular database make use of the USE command:

USE databasename

To display a list of all the databases in your server, use the SHOWDBS command.

show databases

To find the current database you are using, use the db command:

db

Collections

A grouping of MongoDB documents. A collection is the equivalent of a traditional/relational database “Table/Schema”.

A collection exists within a single database.

Types of Collections

  1. Capped Collection
  2. Non-Capped Collection

Capped Collection is a type of collection that has a maximum document count that prevents overflowing documents, it works similar to circular buffers.

It allocates space to the document once the allocated space is filled by overwriting the oldest documents in the collection.

Creating a Capped Collection is as simple as run this code:

db.createCollection("myCappedCollection", {capped : true, size : 2, max : 2})

The size : 2 sets a limit of two megabytes, and max: 2 sets the maximum number of documents to two.

When you insert data above the specified max and size, the data will still be inserted but the oldest will not show up in your queries.

Non-Capped Collection is of course the opposite of Capped Collection and also this is the most popular way of creating collections in MongoDB.

Let’s create a new non capped collection:

db.createCollection("myNonCappedCollection")

The myNonCappedCollection has no limits or max size, so any amount of data can be stored provided you have enough memory.

Documents

As stated above, MongoDB stores its data in BSON documents. BSON is simply a binary representation of JSON that contains more data types than a traditional JSON. 

Read more here about BSON documents.

Because the data is stored in form of JSON therefore, it’s a key-value pair structure as seen in the diagram below.

Image from MongoDB

A clear example of a valid document is:


var mydoc = {
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Solomon", last: "Eseme" },
               birth: new Date('Jun 23, 1960'),
               married: new Date('Jun 07, 1984'),
               contribs: [ "MasteringBackend", "Backend Article", "Backend Videos" ],
            }

The _id holds an ObjectId data type.

The name holds another document containing first and last as Strings.

Then birth and married holds the Date type.

Lastly, the contribs holds the array datatype.

Let’s look at how we can insert a new documents into our collection using the format laid above.

Inserting Data

Inserting documents in MongoDB collections is as simple as creating a valid JSON document and inserting it using one of the following methods of the collection.

The methods are insertOne, insertMany, insert:

InsertOne

This is the most used of all, it is used to insert a single document into the MongoDB collection.


  db.posts.insertOne( 
  {
   "post_title":"This is just a test Post", 
   "post_desc":"This is a test post description",
   "post_author":"Solomon Eseme",
   "post_date":new Date(), 
   "post_tags": "title, post, test",
   "post_category":"Backend" 
  }
)
InsertMany

With this insert method, you can insert more than one document into the collection.

db.posts.insertOne( 
[
  {
   "post_title":"This is just a test Post 0", 
   "post_desc":"This is a test post description",
   "post_author":"Solomon Eseme",
   "post_date":new Date(), 
   "post_tags": "title, post, test",
   "post_category":"Backend" 
  },  
  {
   "post_title":"This is just a test Post 1", 
   "post_desc":"This is a test post description",
   "post_author":"Solomon Eseme",
   "post_date":new Date(), 
   "post_tags": "title, post, test",
   "post_category":"Backend" 
  },  
  {
   "post_title":"This is just a test Post 2", 
   "post_desc":"This is a test post description",
   "post_author":"Solomon Eseme",
   "post_date":new Date(), 
   "post_tags": "title, post, test",
   "post_category":"Backend" 
  }
]
)
Insert

Is a lot similar to insertMany method, it can be used to insert more than one document and also can be used to insert one document too.

How to Retrieve data

Querying data is one of the most performed activities on any database and MongoDB provides clean and clear methods for querying data and data presentation.

With the use of find() method, you can query any data in a collection.

Here is how:

db.posts.find(query, projection)
Query

The optional query parameter specifies the selection filters using Query Operators, you can pass in {} to return all the documents.

Retrieve documents with Query params

Also, you could query data using different parameters and queries, such as:

// Retrieving documents where _ID equals 5
db.posts.find( { _id: 5} ).pretty() 

// Retrieving documents where title equals test
db.posts.find( { "title": "test"} ).pretty() 

// Retrieve documents with Greater than
db.collection.find( { qty: { $gt: 4 } } ) 
Projection

The optional projection specifies the fields that are to be returned with the query.

The fields that match the specified projections will be returned. To return all fields leave the parameter blank.

Query with Projections
db.posts.find( { }, { title: 1, author: 1 } )

This query will retrieve all the posts with only title and author fields.

To retrieve all documents without a parameter:

db.posts.find()

The data will be presented in a none formatted format, like so:

If you want to see the data in a cleaner and well-formatted JSON, you can append the pretty() method to the end of the find() method.

db.posts.find().pretty()

Now the data will be formatted like so:

Of course, there are different other parameters to pass in, and also, there are many methods available to query data such as findOne(), findAndModify(), etc.

A list of all the collection methods and what function they perform can be found here.

ObjectID

Mongo DB auto-generated IDs _id is called ObjectID which are very small, unique, fast to generate, and ordered keys which acts as the primary key for the document.

You can read more about ObjectID here.

Cursor

A cursor is a pointer to a result set of a query when the find() method is executed on a collection, the method returns a Cursor that is iterable and can be iterated to retrieve results.

Query and Projection Operators 

MongoDB provides a variety of different query operators such as Query Selectors, Projection Operators and Miscellaneous Operators.

The most commonly used ones are listed below:

$eq
Matches values that are equal to a specified value.

$gt
Matches values that are greater than a specified value.

$gte
Matches values that are greater than or equal to a specified value.

$in
Matches any of the values specified in an array.

$lt
Matches values that are less than a specified value.

$lte
Matches values that are less than or equal to a specified value.

$ne
Matches all values that are not equal to a specified value.

$nin
Matches none of the values specified in an array.

You can get a complete list of these query and projection operators here and Query Modifiers here.

MongoDB Aggregation

“Aggregation operations process data records and return computed results. Aggregation operations group values from multiple documents together and can perform a variety of operations on the grouped data to return a single result.” from Mongo

MongoDB has a lot of Document Aggregations and a few most used ones include:

Aggregate
Performs aggregation tasks such as groups using the aggregation framework.

Count
Counts the number of documents in a collection or a view.

Distinct
Displays the distinct values found for a specified key in a collection or a view.

MapReduce
Performs map-reduce aggregation for large data sets.

MongoDB Aggregation is divided broadly into different categories and can be found here.

Updating a document

To update a document in MongoDB is simply with the use of the update method of the MongoDB Collection.

Let’s assume with want to update our posts collection where _id equals 5, we will write the command as:

db.posts.update( { _id: 5 }, { $set:{ title: "This is a new post title" } } )

This will update the specific document with the new title specified.

Deleting documents 

Also, removing a particular document is done using the remove method and the same method can be used to remove all the documents in a Collection, so be careful when using it.

To remove a single document, specify a unique parameter:

db.posts.remove( { _id: 5 } )

To remove all documents, run this command:

db.posts.remove({});

It’s important to note that, when deleting all the documents in a Collection, the Collection itself will be deleted too.

Wrapping up

So far, I have discussed the basics of MongoDB in this tutorial that you might need to build applications with MongoDB.

If you want to start building real-world applications with MongoDB right away, I have selected a course and some resources that helped me learn MongoDB below.

MongoDB – The Complete Developer’s Guide 2021 is the best MongoDB course out there to learn and master MongoDB, with this course, you will master MongoDB Development for Web & Mobile Apps.

CRUD Operations, Indexes, Aggregation Framework – All about MongoDB!

  1. Building a Simple CRUD App with Node, Express, and MongoDB
  2. Build a Simple Beginner App with Node, Bootstrap and MongoDB

Conclusion

In this MongoDB tutorial, we have looked at the basics of MongoDB and how to get started with it from the history of MongoDB to installations, creating your first Collections and retrieving, inserting, updating, and deleting documents.

Again, MongoDB – The Complete Developer’s Guide 2021 is the best MongoDB course out there to learn and master MongoDB, with this course, you will master MongoDB Development for Web & Mobile Apps.

CRUD Operations, Indexes, Aggregation Framework – All about MongoDB!

Now, it’s your turn to practice everything you have learned until you master them by building real-world projects.

Let me know what you will be building, if none, just comment “MongoDB is Great”, we may connect from there.

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board

Backend Tips, Every week

Backend Tips, Every week