As far as NoSql databases go, MongoDB is one of the most popular and recognizable options out there. It’s been widely adopted in the Node JS community as the data store for the popular MEAN stack. As a document based NoSql database, MongoDB does not use a table structure like most relational databases and instead stores groups of JSON objects.

Basic Concepts

If you’re used to working with relational databases like MySql and Postgres, you’ll probably find MongoDB’s structure fairly easy to wrap your head around. You can think of MongoDB collections as basically a SQL table without any columns defined. You can also think of MongoDB documents as essentially rows in a SQL table.

While MongoDB doesn’t require any sort of a schema to be implemented, it’s usually best to define some sort of a structure to your documents. This structure should be defined at the application level to make sure any documents being inserted will have the required fields you’ll be reading from in your app.

Installation

MongoDB can be installed on Mac, Windows, and Linux systems. I’m going to be installing on Mac, so if you’re using Windows or Linux I’d recommend taking a look at MongoDB’s documentation as there are slight differences for installation on these platforms.

In general the only steps involved with installing MongoDB are creating a directory to store the database and installing the executables needed to run a Mongo server. The default directory for storing a Mongo database is /data/db, so make sure this directory exists and the user you’re logged in as has write permissions for it.

$ sudo mkdir /data/db
$ sudo chown -R yourusername:wheel /data/db

For installing the MongoDB executables, we’ll be using Homebrew.

$ brew update
$ brew install mongodb

If you’d rather install MongoDB without Homebrew, there are instructions on MongoDB’s website that can guide you through a manual installation.

Running MongoDB

The first step to interacting with MongoDB is starting a MongoDB process. Most MongoDB tutorials around the web will tell you to run MongoDB directly using the mongod command without any arguments.

$ mongod

This works for starting a MongoDB process in the foreground, but I don’t like starting Mongo this way for a couple of reasons. First of all, if you want to run a web app locally that connects to MongoDB, or work with your database directly from the command line, you need to have multiple tabs open in your terminal just to get Mongo up and running. Also, in the event that your machine shuts down while Mongo is running as a process, the lock file for your Mongo process will need to be deleted and you will need to run mongod --repair to start another process.

I generally prefer to run MongoDB as a service. If you installed MongoDB with homebrew you can start MongoDB as a service like this:

$ brew services start mongodb

If you didn’t install Mongo with homebrew, you can use the --fork flag to run MongoDB in the background. When using --fork, you’ll also need to declare where logs will be written to by using --logpath.

$ mongod --fork --logpath /var/log/mongod.log

Once you have Mongo running as a process, you can try connecting to your Mongo instance by using the mongo shell.

$ mongo

Database Commands

MongoDB won’t create a database until something is inserted into it. The trick is to start using your database (even if it doesn’t exist yet), create a collection, and insert a document into that collection.

Try running some of these commands in the mongo shell.

// start using new database
> use new_db

// show current database
> db

// list all databases
> show databases

// insert a document in the "cats" collection
> db.cats.insert({"name": "Theodore", "color": "grey"});

// list all databases again
> show databases

// show all collections in current database
> show collections

CRUD Operations

To create a document in MongoDB, there are two commands that you can use; insert() and save(). The main difference between these two commands is that insert() will always create a new document, but save() can also be used to update existing documents if the document being passed has an “_id” field.

// create a cat document
> db.cats.insert({"_id": 1, "name": "Tommy", "color": "black"});

// update Tommy using save()
> db.cats.save({"_id": 1, "name": "Tommy", "color": "white"});

// find all cat documents
> db.cats.find();

As you can see in the previous code block, we used the find() function to read documents from a collection. You can also pass a query document as a parameter to find() to return all documents with matching fields. There is also a second optional parameter to find() that can be used to define what fields should be returned in each document.

// make another cat
> db.cats.insert({"name": "Marvin", "color": "grey"});

// find all grey cats
> db.cats.find({"color": "grey"});

// only return cat names
> db.cats.find({},{"_id": false, "name": true});

In addition to the save() function we saw earlier, there is also an update() function that can be used to modify existing documents in MongoDB. The parameters for update() are similar to find() with the query document as the first parameter, but the second parameter is used to specify what updates will be made to the document found. There are also optional parameters for creating new documents if none are found and updating multiple documents at the same time.

// update Theodore's color
> db.cats.update({"name": "Theodore"}, {"name": "Theodore", "color": "silver"});

// show all cats
> db.cats.find();

You can delete documents from a collection using the remove() function. There is a required query parameter to specify which documents need to be deleted. Passing an empty document as the query parameter will delete every document in the collection.

// delete Marvin from the collection
> db.cats.remove({"name": "Marvin"});

// delete all cats
> db.cats.remove({});

Final Thoughts

That pretty much covers the basics of using MongoDB. As you can see, setting up a database and changing data within a database can be done fairly quickly with very minimal effort.