MongoDB Crash Course cover image

MongoDB Crash Course

Jonathan Barrios • September 10, 2020

databases

If you've been curious about MongoDB or NoSQL in general, this 20-minute crash course is for you. We'll dive right into the basics and apply them right away using the MongoDB Shell and Compass, an intuitive GUI. While we won't build any projects in this crash course, we will:

Prerequisites

Preferably, you have experience building applications using SQL databases or a basic understanding of SQL basics. Familiarity with the command prompt or terminal to execute commands and install packages is also helpful.

Thank you for joining me in this MongoDB crash course. I hope you can take what you learn here with you on your journey to becoming a better MongoDB developer.

What is MongoDB?

MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL, MongoDB uses JSON-like documents with optional schemas. Unlike relational databases, MongoDB allows you to use records without restrictions, such as using the same number of columns. Relational databases also require you to create every column and specify the data type for each one.

For JavaScript developers, MongoDB is intuitive because it uses BSON to store documents, which is almost identical to JSON. The MEAN and MERN stack's 'M' stands for MongoDB, which gives us an idea of MongoDB's popularity in the JavaScript community.

Primarily, MongoDB accommodates the developer instead of the developer, accomodating the needs of the database.

What is BSON?

BSON is a binary form of JSON representing simple or complex data structures, including associative arrays, integer indexed arrays and fundamental scalar types. BSON originated in 2009 at MongoDB and supports data types that are missing from JSON. For example, JSON only supports numbers for numerical values while BSON supports 'int', 'long', 'float', and 'decimal' binary data types. In short, the Document Model allows us to:

Getting Started

For Windows users, navigate to the MongoDB website and install the MongoDB Community Server. To run the MongoDB Shell, navigate to C:\Program Files\MongoDB\Server\4.4\bin from the command prompt. Additionally, installing the MongoDB Community Server will also install Compass, the graphical UI.

IMG

For macOS, we'll be using Homebrew. To install Homebrew, navigate to the Homebrew website, and follow the instructions. The following commands were copied from the MongoDB website here. Finally, enter the following commands:

IMG

# Install MongoDB with Homebrew
brew tap mongodb/brew

# Install MongoDB community server
brew install [email protected]

# I prefer running mongod in the background
mongod --config /usr/local/etc/mongod.conf --fork

# Open a MongoDB shell
mongo

Note: If running mongod in the background using the code above resulted in an error. Try running the command with sudo in front. While this workaround is okay for testing purposes, be sure to read the MongoDB documentation to learn more about configuration files and security best practices.

To stop MongoDB running in the background:

Install Compass

Windows users will already have Compass installed while macOS users will not because Homebrew didn’t install it. To install Compass, navigate to the Compass download page and follow the directions.

IMG

Once you have Compass running, click on Fill in connection fields individually. If you don't need to change ports, click on CONNECT to get started. The admin, config, and local databases displayed are the defaults, which means we are connected.

IMG

Create a new database

In this section, we'll create a new database and use the database creation form. First, create a database by clicking on the CREATE DATABASE button, then enter a database name and a collection name; I will call my database z_bookshop and my collection books.

IMG

It’s worth noting that a Collection is similar to a Table in relational databases. Additionally, MongoDB stores BSON documents inside of collections, not columns and rows commonly found inside of Tables in relational databases.

IMG

Once Compass creates our database and collection, we'll see the new database in Compass. Click on the z_bookshop database, then click on books to insert data into our new collections.

IMG

To add a document, click on ADD DATA, select Insert Document, and a pop-up will appear.

Click on the list icon to change views then take a look at the _id paired to an ObjectId––think of this as a Primary Key compared to relational databases.

IMG

To create a new record, add a title as the key, followed by the "MongoDB Crash Course value".

IMG

The MongoDB Shell

Now that we are comfortable with Compass basics, we can start working in the MongoDB shell. If you didn’t start the shell earlier, you could do so now in the Terminal by typing: mongo.

We can view our databases in the shell by typing the show dbs command, displaying three default databases, and the z_bookshop database.

IMG

Let's select and use our new database with the use command, followed by the database name we want to use. In our case, use z_bookshop. You can also use the show collections command to display collections in the shell.

The previous commands return the databases and books collection, as expected. Next, we’ll delete our database, z_bookshop, and create a new database in the shell from scratch.

IMG

To delete the current database, use the db.dropDatabase() method, as shown here. Use the show dbs command again, and we'll only see three databases listed and not four––we deleted or "dropped" the fourth database, z_bookshop.

IMG

To create a new database and switch to it using one command, enter the use command, followed by the database's name. In my case, I will enter use x_bookshop, which returns a success message, as shown.

IMG

Invoking the use command on a non-existing database creates a new database then switches to it, making this command very useful.

If we try to use the show dbs command now, we won't see anything because our new database, x_bookshop, is empty. To see which database we are currently working in, feel free to type db in the MongoDB shell at any time.

To create a collection for the empty database, use the db.createCollection('books') command. The { “ok” : 1 } message returned in the shell, indicates that we successfully added the books collection to our database.

IMG

IMG

Finally, use the show collections command to reveal that we indeed have a new collection called books, way to go!

Insert Data

Now that you have a database and a collection, you can start adding data using the insert() method, as shown here. Inside the insert() method, we have a title, excerpt, and author wrapped in curly braces. Everything inside of the insert() method has a key:value pair and represents a document.

db.books.insert({
  title: 'MongoDB Crash Course',
  excerpt:
    'MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.',
  author: 'Jonathan Barrios',
})

// Returns
WriteResult({ nInserted: 1 })

We can also add more than one insert using insertMany like this:

db.books.insertMany([
  {
    title: 'MongoDB Crash Course',
    excerpt:
      'MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.',
    author: 'Jonathan Barrios',
  },
  {
    title: 'JavaScript Crash Course',
    excerpt: 'About this book.',
    author: 'Jonathan Barrios',
  },
  {
    title: 'React Crash Course',
    excerpt: 'About this book.',
    author: 'Jonathan Barrios',
  },
])

// Returns
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5f320282fd6ad01ea40dbe4d"),
                ObjectId("5f320282fd6ad01ea40dbe4e"),
                ObjectId("5f320282fd6ad01ea40dbe4f")
        ]
}

To manually verify that our records are inside our database, we can use the find() method. Using the find() method will look a little messy, much like reading unformatted JSON can be messy and hard to read. Instead, we can chain commands and use the pretty() method to clean things up. Enter db.books.find().pretty() and violá, we have pretty looking JSON data.

To sort our books in both ascending and descending order, we can use the sort() method, as shown. The -1 in the descending command is just the opposite of 1, which is another way of saying, start sorting with the last book, or in descending order.

// Ascending
db.books
  .find()
  .sort({ title: 1 })
  .pretty()

//  Descending
db.books
  .find()
  .sort({ title: -1 })
  .pretty()

MongoDB allows you to chain functions together to sort and limit the number of books you get back. To find, sort, and limit your MongoDB query, use the following command, as shown here.

db.books
  .find()
  .sort({ title: 1 })
  .limit(2)
  .pretty()

How about a forEach loop with a function? No sweat, use the forEach() method with the following command, as shown. Once you enter the command, the MongoDB shell returns a neat list of books with custom strings for each one.

db.books.find().forEach(function(doc){ print('Book title: ' + doc.title) })

// Returns
Book title: MongoDB Crash Course
Book title: MongoDB Crash Course
Book title: JavaScript Crash Course
Book title: React Crash Course

To exit the MongoDB shell, type: exit

Documentation

These are just some of the basics I wanted to present as part of the MongoDB Crash Course. To learn more, check out the MongoDB documentation, MongoDB University, and the developer community.

Compass Review

Let's open Compass and review everything we've created so far. Click on x_bookshop, and we'll see the books collection, and if we click on that, we'll see our database records. I hope this crash course helps you use MongoDB in your future projects for a better internet. As always, happy coding! 🙌🏼