MongoDB Overview

Let's learn about the basics of MongoDB and how we can use it.

As indicated by the “M” in MERN, we’ll use MongoDB as the back-end database for our application. MongoDB is a NoSQL database. Before we talk about what a NoSQL database is, let’s first talk about relational databases so we can provide a meaningful contrast.

Relational databases

We can think of relational databases as spreadsheets in which data is structured and each entry is a row in a table. SQL (or Structured Query Language) usually controls relational databases. Examples of popular relational databases are MySQL, SQL Server, and PostgreSQL.

NoSQL databases

In contrast, NoSQL databases are often called non-relational databases, with NoSQL meaning anything that isn’t SQL. It might seem like NoSQL is a protest over SQL, but it refers to a database that isn’t structured like a spreadsheet. In other words, they are less rigid than SQL databases.

MongoDB

MongoDB is a NoSQL database that stores information in the form of collections and documents. MongoDB stores one or more collections. A collection represents a single entity in our application. For example, in an e-commerce app, we need entities like categories, users, and products. Each of these entities will be a single collection in our database.

If we were to map similar concepts in relational databases and MongoDB:

  • A table in a relational database would compare to a collection in MongoDB.

  • Each row in a table in a relational database can be thought of as a document that is part of a collection in MongoDB.

  • The $lookup method in MongoDB carries out JOIN operations.

  • Instead of foreign keys, MongoDB utilizes references.

In MongoDB, a collection contains documents. A document is a singular data object instance containing the various relevant field values. For example, a product document may contain title, description, and price fields. Each field is a key-value pair—for example, price: 26 and title: "Learning Node". Documents look like JSON objects with various properties (though they are technically Binary JSON).

JSON is a text-based format for storing structured data based on JavaScript object syntax and Binary JSON (BSON) is a binary encoding of JSON documents.

Press + to interact
Database
Products collection
Product document {
price: 26,
title: "Learning Node",
description: "Top Notch Development book", expiry date: 27-3-2020
}
Product document
...
Users collection
User document {
username: "123xyz", contact:
{
phone: "123-456-7890", email: "xyz@example.com"
}
}
User document
...

Let’s take a look at an example of a collection-document tree in the code widget above. We can see that we have a variety of relationships. A user has a username and contact. Within contact, we have phone and email. The BSON format provides a wide variety of support for data types such as strings, integers, etc.