How to get started with MongoDB in 10 minutes

Navindu Jayatilake
Jan 27, 2019 · 9 min read
Image for post
Image for post

MongoDB is a rich document-oriented NoSQL database.

If you are a complete beginner to NoSQL, I recommend you to have a quick look at my NoSQL article published previously.

Today, I wanted to share some of the basic stuff about MongoDB commands such as querying, filtering data, deleting, updating and so on.

Okay, enough of the talk, let’s get to work!

Configuration 🔧

In order to work with MongoDB, first you need to install MongoDB on your computer. To do this, visit the official download center and download the version for your specific OS. Here, I’ve used Windows.

After downloading MongoDB community server setup, you’ll go through a ‘next after next’ installation process. Once done, head over to the C drive in which you have installed MongoDB. Go to program files and select the MongoDB directory.

In the bin directory, you’ll find an interesting couple of executable files.

  • mongod
  • mongo

Let’s talk about these two files.

mongod stands for “Mongo Daemon”. mongod is a background process used by MongoDB. The main purpose of mongod is to manage all the MongoDB server tasks. For instance, accepting requests, responding to client, and memory management.

mongo is a command line shell that can interact with the client (for example, system administrators and developers).

Now let’s see how we can get this server up and running. To do that on Windows, first you need to create a couple of directories in your C drive. Open up your command prompt inside your C drive and do the following:

The purpose of these directories is MongoDB requires a folder to store all data. MongoDB’s default data directory path is on the drive. Therefore, it is necessary that we provide those directories like so.

If you start the MongoDB server without those directories, you’ll probably see this following error:

Image for post
Image for post
trying to start mongodb server without \data\db directories

After creating those two files, head over again to the bin folder you have in your mongodb directory and open up your shell inside it. Run the following command:

Voilà! Now our MongoDB server is up and running! 😎

In order to work with this server, we need a mediator. So open another command window inside the bind folder and run the following command:

After running this command, navigate to the shell which we ran mongod command (which is our server). You’ll see a ‘connection accepted’ message at the end. That means our installation and configuration is successful!

Just simply run in the mongo shell:

Image for post
Image for post
initially you have a db called ‘test’

Setting up Environment Variables

To save time, you can set up your environment variables. In Windows, this is done by following the menus below:

Simply copy the path of our bin folder and hit OK! In my case it’s

Now you’re all set!

Working with MongoDB

There’s a bunch of GUIs (Graphical User Interface) to work with MongoDB server such as MongoDB Compass, Studio 3T and so on.

They provide a graphical interface so you can easily work with your database and perform queries instead of using a shell and typing queries manually.

But in this article we’ll be using command prompt to do our work.

Now it’s time for us to dive into MongoDB commands that’ll help you to use with your future projects.

  1. Open up your command prompt and type to start the MongoDB server.

2. Open up another shell and type to connect to MongoDB database server.

1. Finding the current database you’re in

Image for post
Image for post

This command will show the current database you are in. is the initial database that comes by default.

2. Listing databases

Image for post
Image for post

I currently have four databases. They are: , , and .

3. Go to a particular database

Image for post
Image for post

Here I’ve moved to the database. You can check this if you try the command to print out the current database name.

4. Creating a Database

With RDBMS (Relational Database Management Systems) we have Databases, Tables, Rows and Columns.

But in NoSQL databases, such as MongoDB, data is stored in BSON format (a binary version of JSON). They are stored in structures called “collections”.

In SQL databases, these are similar to Tables.

Image for post
Image for post
Image for post
Image for post
SQL terms and NoSQL terms by Victoria Malaya

Alright, let’s talk about how we create a database in the mongo shell.

Wait, we had this command before! Why am I using it again?!

In MongoDB server, if your database is present already, using that command will navigate into your database.

But if the database is not present already, then MongoDB server is going to create the database for you. Then, it will navigate into it.

After creating a new database, running the command will not show your newly created database. This is because, until it has any data (documents) in it, it is not going to show in your db list.

5. Creating a Collection

Navigate into your newly created database with the command.

Actually, there are two ways to create a collection. Let’s see both.

One way is to insert data into the collection:

This is going to create your collection even if the collection does not exist. Then it will insert a document with and . These are non-capped collections.

The second way is shown below:

2.1 Creating a Non-Capped Collection

2.2 Creating a Capped Collection

In this way, you’re going to create a collection without inserting data.

A “capped collection” has a maximum document count that prevents overflowing documents.

In this example, I have enabled capping, by setting its value to .

The means a limit of two megabytes, and sets the maximum number of documents to two.

Now if you try to insert more than two documents to and use the command (which we will talk about soon), you’ll only see the most recently inserted documents. Keep in mind this doesn’t mean that the very first document has been deleted — it is just not showing.

6. Inserting Data

We can insert data to a new collection, or to a collection that has been created before.

Image for post
Image for post
ways data can be stored in a JSON

There are three methods of inserting data.

  1. is used to insert a single document only.
  2. is used to insert more than one document.
  3. is used to insert documents as many as you want.

Below are some examples:

  • insertOne()
  • insertMany()

The method is similar to the method.

Also, notice we have inserted a new property called on the document for . So if you use , then you’ll see only for the property is attached.

This can be an advantage when it comes to NoSQL databases such as MongoDB. It allows for scalability.

Image for post
Image for post
Successfully inserted data

7. Querying Data

Here’s how you can query all data from a collection:

Image for post
Image for post
result

If you want to see this data in a cleaner, way just add to the end of it. This will display document in pretty-printed JSON format.

Image for post
Image for post
result

Wait...In these examples did you just notice something like ? How did that get there?

Well, whenever you insert a document, MongoDB automatically adds an field which uniquely identifies each document. If you do not want it to display, just simply run the following command

Next, we’ll look at filtering data.

If you want to display some specific document, you could specify a single detail of the document which you want to be displayed.

Image for post
Image for post
result

Let’s say you want only to display people whose age is less than 25. You can use to filter for this.

Similarly, stands for greater than, is “less than or equal to”, is “greater than or equal to” and is “not equal”.

8. Updating documents

Let’s say you want to update someone’s address or age, how you could do it? Well, see the next example:

The first argument is the field of which document you want to update. Here, I specify for the simplicity. In production environment, you could use something like the field.

It is always better to use something like to update a unique row. This is because multiple fields can have same and . Therefore, if you update a single row, it will affect all rows which have same name and age.

Image for post
Image for post
result

If you update a document this way with a new property, let’s say for example, the document will be updated with the new attribute. And if you do a , then the result will be:

Image for post
Image for post
result

If you need to remove a property from a single document, you could do something like this (let’s say you want to be gone):

9. Removing a document

As I have mentioned earlier, when you update or delete a document, you just need specify the not just , , .

10. Removing a collection

Note, this is not equal to the method. The difference is is used to remove all the documents inside a collection, but the method is used to delete all the documents along with the collection itself.

Logical Operators

MongoDB provides logical operators. The picture below summarizes the different types of logical operators.

Image for post
Image for post
Image for post
Image for post
reference: MongoDB manual

Let’s say you want to display people whose age is less than 25, and also whose location is Colombo. What we could do?

We can use the operator!

Last but not least, let’s talk about aggregation.

Aggregation

A quick reminder on what we learned about aggregation functions in SQL databases:

Image for post
Image for post
aggregation functions in SQL databases. ref : Tutorial Gateway

Simply put, aggregation groups values from multiple documents and summarizes them in some way.

Imagine if we had male and female students in a collection and we want a total count on each of them. In order to get the sum of males and females, we could use the aggregate function.

Image for post
Image for post
result

Wrapping up

So, we have discussed the basics of MongoDB that you might need in the future to build an application. I hope you enjoyed this article…Thanks for reading!

If you have any queries regarding this tutorial, feel free to comment out in the comment section below or contact me on Facebook or Twitter or Instagram.

See you guys in the next article! ❤️ ✌🏼

Link to my previous article: NoSQL

freeCodeCamp.org

This is no longer updated.

Navindu Jayatilake

Written by

Self-taught Web Developer | Writer | Software Engineering Undergraduate | DevOps Enthusiast

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Navindu Jayatilake

Written by

Self-taught Web Developer | Writer | Software Engineering Undergraduate | DevOps Enthusiast

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store