DEV Community

Cover image for MongoDB Guide - Getting Started
Douglas Minnaar
Douglas Minnaar

Posted on

MongoDB Guide - Getting Started

Summary

In this guide, I am going to cover the essentials in terms of getting up and running with MongoDB. The best way to start learning new technology is to jump straight in and start using it. Therefore, after a brief introduction to MongoDB, the following sections are all about setting up your own MongoDB instance using 4 different hosting methods. Next, I introduce 5 tools that you can use to work with your MongoDB databases. The next section illustrates methods on creating your own database and collection with data. In this section I also provide a number of examples that illustrate some basic queries to query your data.

This guide is summarized as follows:

  • What Is MongoDB
  • MongoDB Setup
    • Install And Host Locally
    • Install And Host Using Docker
    • Host With MongoDB Atlas
    • Host With MLab
  • MongoDB Tools
    • MongoDB Shell
    • MongoDb Compass
    • NoSqlBooster
    • Robo 3T
    • Visual Studio Code
  • Basic MongoDB Commands
  • Conclusion

Lastly, this guide does not cover the reasons to use MongoDB (perhaps a guide for another time). However, I would like to encourage readers to spend some time researching and understanding the rationale between choosing a NoSql database over a Sql database. MongoDB is not a replacement for SQL databases. It is merely an alternative that may (or may not) align better with ones specific requirements.

The following question posted on Quora may be a good starting point:

What are some reasons to use traditional RDBMS over NoSQL?

From my personal experience and perspective, I will mention that one should think very carefully before committing to a NoSql database if your data is required to be agnostic. In this case I have found Sql databases to be a far better choice due to the simplicity of modelling data and exposing it in many different ways for many different applications.

The original guide can be found on my Github repository. Like my Docker Guide, I will be updating and adding more content over time to this repository.


What Is MongoDB?

MongoDB is a database. More specifically, it is an open source document-oriented database that has been designed for scalability and simplicity for both developers and sysadmins. Traditional relational database management systems (RDBMS) like MSSQL, Oracle, MySQL, and PostGreSQL store data in tables having a static schema composed of rows and columns. However, MongoDB stores it's data in JSON-like documents having dynamic schemas.


MongoDB Setup

I will discuss 4 options to get up and running with MongoDB:

  • Install and host locally
  • Install and host in Docker
  • Register for and use MongoDB Atlas (Database As A Service)
  • Register for and use MLab (Database As A Service)

Install And Host Locally

Installing MongoDB is relatively straight forward. There are currently 3 platform (Windows, Linux, OSX) releases available and can be found here

For more specific installation instructions, please see the following links:

Install And Host Using Docker

If you have never used Docker before, then this option is less suitable for you as it implies having some Docker knowledge and experience. However, if you are still interested in pursuing this option, then I recommend viewing my Docker Guide as a starting point. I also have a Docker Cheatsheet that you may find useful.

The Docker image that will be used, is the official Docker MongoDB image.

Run MongoDB

Run MongoDB Using Named Volume

For the following examples I map the Docker MongoDB port of 27017 to a local port of 37017. The reason for this is because I have a local instance on MongoDB running that is already using the 27017 port.

To run a new MongoDB container, execute the following command from the CLI:

docker run --rm --name mongo-dev -p 37017:27017 -v mongo-dev-db:/data/db -d mongo
Enter fullscreen mode Exit fullscreen mode
CLI Command Description
--rm remove container when stopped
--name mongo-dev give container a custom name
-p map container published port to local port
-v mongo-dev-db/data/db map the container volume 'data/db' to a custom name 'mongo-dev-db'
-d mongo run mongo container as a daemon in the background
Run MongoDB Using Bind Mount
cd
mkdir -p mongodb/data/db
docker run --rm --name mongo-dev -p 37017:27017 -v ~/mongodb/data/db:/data/db -d mongo
Enter fullscreen mode Exit fullscreen mode
CLI Command Description
--rm remove container when stopped
--name mongo-dev give container a custom name
-p map container published port to local port
-v ~/mongodb/data/db/data/db map the container volume 'data/db' to a bind mount '~/mongodb/data/db'
-d mongo run mongo container as a daemon in the background

Access MongoDB

Access MongoDB From Local Machine
  1. Type the following command to access MongoDB instance hosted within docker container:
   mongo --host localhost --port 37017
Enter fullscreen mode Exit fullscreen mode
Access MongoDB Via Docker Interactive TTY

There are 2 steps to accessing the MongoDB shell.

  1. Firstly, access the MongoDB container shell by executing the following command:
   docker exec -it mongo-dev bash
Enter fullscreen mode Exit fullscreen mode

This will open an interactive shell (bash) on the MongoDB container.

  1. Secondly, once inside the container shell, access the MongoDB shell by executing the following command:
   mongo localhost
Enter fullscreen mode Exit fullscreen mode

Host With MongoDB Atlas

MongoDB Atlas is a Data as a Service (DaaS) offering, and is hosted in the cloud. There is no installation of MongoDB required and a free tier is available.

To get started, signup for free by registering for a free tier account here. The free tier entitles you to 512MB storage.

Please review the [MongoDB Atlas Documentation] for more information.

Once you have registered and setup your MongoDB instance on Atlas, you will be presented with a dashboard resembling the following image:

atlas

Host With MLab

MLab is a Data as a Service (DaaS) offering, and is hosted in the cloud. There is no installation of MongoDB required and a free tier is available.

To get started, signup for free account here. The free tier entitles you to 500MB storage.

Please review the MLab Documentation for more information.

Once you have registered and setup your MongoDB instance on MLab, you will be presented with a dashboard resembling the following image:

mlab


MongoDB Tools

The tooling for MongoDB has improved a lot of late and there are many options. I have worked with the following tools and I find them all quite good. It's really a matter of personal preference but I find that I tend to use them together.

MongoDB shell

The MongoDB shell is the default way of interacting with MongoDB databases.

  • Connect to MongoDB
  mongo localhost
Enter fullscreen mode Exit fullscreen mode
  • List Available Databases
  show dbs
Enter fullscreen mode Exit fullscreen mode
  • Create Database
  use message_db
Enter fullscreen mode Exit fullscreen mode
  • Create Collection
  db.messages.insert({ message: 'hello mongodb' })
Enter fullscreen mode Exit fullscreen mode
  • List Collections
  show collections
Enter fullscreen mode Exit fullscreen mode

MongoDB Compass

MongoDB Compass is a Graphical User Interface (GUI) tool that allows one to explore your MongoDB data.

  • It has a free addition available
  • It is cross platform and is available for Linux, Windows, and Mac
  • It supports the following primary features:

    • Run ad hoc queries
    • Perform CRUD operations on data
    • View and optimize query performance

In the following screenshot, I am connected to MongoDB running on my local machine, using MongoDB Compass.

compass

For more information on MongoDB Compass, go here

NoSqlBooster

NoSqlBooster is a Graphical User Interface (GUI) that provides an easy to use interface to work with your MongoDB database.

  • It has a free addition available
  • It is cross platform and is available for Linux, Windows, and Mac
  • It provides the following features:

    • Shell extensions
    • Fluent Query API for MongoDB
    • Query MongoDB with SQL
    • Use Node Modules in your script

In the following screenshot, I am connected to MongoDB running on Docker, using NoSqlBooster.

nosqlbooster

For more information, please visit the official NoSqlBooster website.

Robo 3T

Robo 3T, is a free GUI tool that can be used to explore your MongoDB databases.

  • It is free to use.
  • It is cross platform and is available for Linux, Windows, and Mac
  • It provides a MongoDB GUI with embedded shell

In the following screenshot, I am connected to a local instance of MongoDB using Robo 3T:

robo3t

Robo 3T can be downloaded here

For more information, go here.

Visual Studio Code

Using the Azure CosmosDB Extension, one can connect to MongoDB databases in addition to Azure CosmosDB databases.

For more information, see the following links:

Install Azure CosmosDB Extension

  • Launch VS Code
  • Launch Quick Open (ctrl+P) from within VS Code
  • Paste the following command and press enter
  ext install ms-vscode.vscode-azureextensionpack
Enter fullscreen mode Exit fullscreen mode

Configure User Settings

Once you have the extension installed, you will need to ensure that you have a path to Mongo configured in your user settings. Press Ctrl+, to open your user settings. Therefore, because I am using a Linux based OS, I had to add the following setting to the user settings json:

"mongo.shell.path": "/var/lib/mongodb",
Enter fullscreen mode Exit fullscreen mode

Connect To Mongo On localhost

To connect to MongoDB instance, follow the following steps:

  • Expand Azure Cosmos DB extension panel located in explorer
  • Select the option to 'Attach Database Account'
  • Select MongoDB
  • Enter the connection details to MongoDB instance
  mongodb://localhost:27017
Enter fullscreen mode Exit fullscreen mode

The steps are shown below:

vs-code-cosmodb-ext

Run Commands Using Mongo ScrapBooks

To use the 'ScrapBook Feature', follow the following steps:

  • Attach to your MongoDB instance as seen above
  • Connect to database of your choice
  • Select 'New MongoDB ScrapBook' option to open scrapbook editor
  • Enter MongoDB command
  • Press Ctrl+Shft+' to execute

The steps are shown below:

vs-code-scrapbook

At the time of this writing, there seems to be an issue with Mongo ScrapBooks


Basic MongoDB Commands

Once you have your MongoDB instance running or hosted, open a mongo shell to your MongoDB server. For the purposes of this demonstration, I will be using my local installation 'localhost'.

  • Connect to MongoDB instance
  mongo localhost
Enter fullscreen mode Exit fullscreen mode
  • Create a 'zips_db' database
  use zips_db
Enter fullscreen mode Exit fullscreen mode
  • Create 'zips' collection
  db.zips.insertMany([
     { "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 5338, "state" : "MA", "_id" : "01001" },
     { "city" : "CUSHMAN", "loc" : [ -72.51564999999999, 42.377017 ], "pop" : 36963, "state" : "MA", "_id" : "01002" },
     { "city" : "BARRE", "loc" : [ -72.10835400000001, 42.409698 ], "pop" : 4546, "state" : "MA", "_id" : "01005" },
     { "city" : "BELCHERTOWN", "loc" : [ -72.41095300000001, 42.275103 ], "pop" : 10579, "state" : "MA", "_id" : "01007" },
     { "city" : "BLANDFORD", "loc" : [ -72.936114, 42.182949 ], "pop" : 240, "state" : "MA", "_id" : "01008" },
     { "city" : "BRIMFIELD", "loc" : [ -72.188455, 42.116543 ], "pop" : 706, "state" : "MA", "_id" : "01010" },
     { "city" : "CHESTER", "loc" : [ -72.988761, 42.279421 ], "pop" : 688, "state" : "MA", "_id" : "01011" },
     { "city" : "CHESTERFIELD", "loc" : [ -72.833309, 42.38167 ], "pop"  177, "state" : "MA", "_id" : "01012" },
     { "city" : "CHICOPEE", "loc" : [ -72.607962, 42.162046 ], "pop" : 3396, "state" : "MA", "_id" : "01013" },
     { "city" : "CHICOPEE", "loc" : [ -72.576142, 42.176443 ], "pop" : 1495, "state" : "MA", "_id" : "01020" }
   ])
Enter fullscreen mode Exit fullscreen mode
  • Search Queries

    • Get total collection count
  db.zips.count()
Enter fullscreen mode Exit fullscreen mode
  • Get all zip documents
  db.zips.find().pretty()
Enter fullscreen mode Exit fullscreen mode
  • Get 5 zip documents
  db.zips.find().limit(5).pretty()
Enter fullscreen mode Exit fullscreen mode
  • Get zip having a city name of 'BLANDFORD'
  db.zips.find({"city": "BLANDFORD"})
Enter fullscreen mode Exit fullscreen mode
  • Get zip having a city name of 'BLANDFORD', ignore case
  db.zips.find({"city": { "$regex": /blandford/i } })
Enter fullscreen mode Exit fullscreen mode
  • Get zip having a city names of 'BLANDFORD' and 'BRIMFIELD'
  db.zips.find({"city": { "$in": ["BLANDFORD", "BRIMFIELD"] } }).pretty()
Enter fullscreen mode Exit fullscreen mode
  • Get zip having a city names of 'BLANDFORD' and 'BRIMFIELD', ignore case
  db.zips.find({"city": { "$in": [ /blandford/i, /brimfield/i] } }).pretty ()
Enter fullscreen mode Exit fullscreen mode
  • Get zip documents having a population greater than or equal to 30000
  db.zips.find({"pop": { "$gte": 30000}}).pretty()
Enter fullscreen mode Exit fullscreen mode
  • Get all zip documents and use projection to only display city and population
  db.zips.find({}, { "city": 1, "pop": 1, "_id": 0 })
Enter fullscreen mode Exit fullscreen mode
  • Get all zip documents and use projection to only display city and population. Sort documents by city name in descending order
  db.zips.find({}, { "city": 1, "pop": 1, "_id": 0 }).sort({"city": -1})
Enter fullscreen mode Exit fullscreen mode
  • Delete operations

    • Delete all cities called 'CHICOPEE'. Ignore case
  db.zips.remove({ "city": { "$regex": /chicopee/i }})
Enter fullscreen mode Exit fullscreen mode
  • Update operations

    • Update the city of 'BLANDFORD' by setting its population to 10
  db.zips.updateOne({"city": "BLANDFORD"}, { "$set": { "pop": 10}})
Enter fullscreen mode Exit fullscreen mode

Conclusion

This has been a quick introduction to getting started with MongoDB. In this guide we learned about 4 different ways to host your MongoDB instance. We also learned about 5 different tools that can be used to manage your MongoDB databases. Lastly, we explored some basic queries that can be used to create a database, create a collection, insert data, update data, and fetch data.

MongoDB is an exciting and relatively new database that has a massive community and knowledgebase. I encourage all those that are interested to get involved by trying out the following learning resources:

The following MongoDB book is my personal favourite:

If you're interested in certification, please see the MongoDB Professional
Certification Program
.


Top comments (4)

Collapse
 
stoimenov95 profile image
Antonio • Edited

I am new with MongoDb and i can say it's pretty easy to use it, especially with node js. NoSQL databases can offer a lot, of course if your tasks don't require strict schemas. Thank you for the nice introduction to mongo, it was helpful.

Collapse
 
drminnaar profile image
Douglas Minnaar

I'm glad you found it helpful. I highly recommend MongoDB University if you're just starting out. In fact, I recommend it to anyone. I've done a few of the courses in preparation for the MongoDB certification exams but still learned quite a bit even though I have some experience. I actively use MongoDB using C#, Python, and Javascript. I tend to work directly with the MongoDB drivers. However, if you're using Javascript be sure to investigate Mongoose as an abstraction of the MongoDB drivers. With regards to NoSQL databases, they do offer a lot when applied to an appropriate architecture. Be sure to check out Couchbase too.

Collapse
 
krumpez profile image
Amine

great post, it says you develop sport betting systems, do you need a good knowledge of probability and statistics to do that ?

Collapse
 
drminnaar profile image
Douglas Minnaar

I'm glad you liked post. With regards to sport betting systems, you do indeed need to have a firm grasp on probability and statistics. I have worked in so many industries from banking through insurance, and medical. However, no industry has required me to have as much knowledge of mathematics as sport betting. A large part of building sport betting systems is building risk management and that's where things get really interesting. I've heard of some sport betting companies having a team of actuaries to assist in this regard.