Tutorial

An Introduction to MongoDB

Draft updated on Invalid Date
Default avatar

By Chris on Code

An Introduction to MongoDB

This tutorial is out of date and no longer maintained.

Introduction

MongoDB has declared itself the leading NoSQL database based on their statistics and it’s hard to argue that it isn’t popular.

MongoDB has been used in the beloved MEAN stack. The benefits of using a document database like MongoDB means that you can work with JSON-style documents across your entire development stack.

You are able to work with JSON on the frontend (Angular), the backend (Node), and the database (MongoDB).

For more benefits to MongoDB, be sure to check out the official site. Let’s get into installing and taking MongoDB for a quick test run.

Installation and Running MongoDB

Getting MongoDB installed on your computer carries with it some simple steps. They are:

  1. Run the MongoDB installation
  2. Create a physical directory for items to be stored

Just like that, we’ll be able to use MongoDB locally!

Note: The following instructions are for Mac users, MongoDB provides great installation instructions for Windows and Linux as well.

The default folder when installing will be /data/db. This is where everything will be stored and you must make sure that you have permissions to this folder so that MongoDB can write to it.

We can install on Macs using either Homebrew or manually. We’ll be focusing on Homebrew for this article.

  1. # update your packages
  2. brew update
  3. # tap custom homebrew tap
  4. brew tap mongodb/brew
  5. # install mongoDB
  6. brew install mongodb-community@5.0

Note: Previously, these instructions suggested installing a mongodb formulae. This method of installation appears to be no longer supported.

If you would prefer not to use Homebrew, the MongoDB site gives other instructions.

Getting Started Using MongoDB

There are two steps to get working with MongoDB locally:

  1. Start the process
  2. Connect

Sounds simple enough! Let’s get to it!

Starting MongoDB Service

Before we can start creating and saving documents in our database, we have to start up MongoDB. There won’t be anything to save to if the service isn’t started! The command is very simple to get MongoDB up and running:

  1. mongod

Once we have issued this command, MongoDB will start up and you should see: waiting for connections on port 27017

Connecting to the MongoDB Service

With our MongoDB service running, we just have to connect to it. While mongod starts MongoDB, the command to connect to it is:

  1. mongo

We are now connected and are able to issue our MongoDB commands.

Notice on the right side, we have connected, and on the left side, our connection has been logged.

Common Database Commands

List All Databases

  1. show dbs

Creating a Database

MongoDB will not create a database unless you insert information into that database.

The trick is you don’t have to worry about explicitly creating a database! You can just use a database (even if it’s not created), create a collection and document, and everything will automatically be made for you!

We’ll look at creating collections and documents in the CRUD Commands section.

Show Current Database

  1. db

Select a Database

  1. use db_name

CRUD Commands

Create

  1. // save one user
  2. db.users.save({ name: 'Chris' });
  1. // save multiple users
  2. db.users.save([{ name: 'Chris'}, { name: 'Holly' }]);

By saving a document into the users collection of the database you are currently in, you have successfully created both the database and collection if they did not already exist.

Read

  1. // show all users
  2. db.users.find();
  1. // find a specific user
  2. db.users.find({ name: 'Holly' });

Update

  1. db.users.update({ name: 'Holly' }, { name: 'Holly Lloyd' });

Delete

  1. // remove all
  2. db.users.remove({});
  1. // remove one
  2. db.users.remove({ name: 'Holly' });

This is just a quick overview of the types of commands you can run. The MongoDB docs are quite comprehensive and provide a great deal of detail for those that want to dive deeper.

MongoDB also provides a great interactive tutorial for you to walk through the above commands.

Using In a Node.js Application

Using a local instance of MongoDB is a very simple process. We will use mongooseJS, the Node package for working with MongoDB.

All you have to do is configure mongoose to connect to a local database. This is a simple process since we don’t even need to create the database. We just have to make sure that MongoDB is running by running:

  1. mongod

We will also give mongoose a database name to connect to (it doesn’t need to be created since mongoose will create it for us).

Here’s some sample code to connect to a database in Node.

// grab the packages we need
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/db_name');

That’s it! Once we start saving things into our database, that database named db_name will automatically be created.

For more information on using Mongoose inside of a Node application, read: Using MongooseJS in Node.js and MongoDB Applications.

GUI Tool: Robomongo

While it’s easy enough to use our command line to get into our MongoDB databases, there’s also a GUI for those that are inclined.

Go ahead and download Robomongo and fire it up.

Creating a connection to our database is very easy. Just set the address to localhost and the port to 27017. Name your connection anything you want.

Then once you connect, you have access to all the databases and their respective collections! You now have a GUI to handle database operations and you can even open a shell to get down and dirty with the commands we discussed earlier.

Conclusion

MongoDB is a great NoSQL database that can be configured quickly and used in any of our applications. For Node applications, we can start up MongoDB quickly so that we can get to the fun part, building applications!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Chris on Code

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel