Introduction to MongoDB and Installation

Learn what MongoDB is, how it differs from MySQL, and how to run and connect to MongoDB locally with Docker.

🎯 Introduction

Welcome to the first lesson in this introductory MongoDB course. If you took the previous MySQL course, MongoDB introduces a different approach: instead of creating tables and writing SQL, you store JSON-like documents directly. This should feel familiar if you work with frontend code.

By the end, you will understand what MongoDB is and how it differs from MySQL, run MongoDB 8 locally with Docker, connect with mongosh, and insert and retrieve your first document. This environment will support the rest of the course.


🧱 What Is MongoDB?

MongoDB is an open-source NoSQL document database. Let's break down those terms:

  • NoSQL: A broad category of databases that do not use traditional SQL table structures. They do not require you to define a table schema in advance, giving you more flexibility in how you store data.
  • Document database: Data is stored as documents, with a format similar to JSON. Internally, MongoDB uses BSON, which you can think of as JSON with additional data types.

MySQL data resembles an Excel spreadsheet: you define columns first, and every row follows that structure. MongoDB data resembles JSON objects: each object contains its own field names and values, and their structures can differ. For example, a user document might look like this:

{
    "_id": ObjectId("66f1a2b3c4d5e6f7a8b9c0d1"),
    "username": "Xiao Ming",
    "age": 20,
    "city": "Beijing",
    "hobbies": ["basketball", "photography"]
}

A few points to note:

  • _id is the document's primary key. MongoDB automatically generates a unique ObjectId when you insert a document, serving a similar purpose to an auto-incrementing primary key in MySQL.
  • Field values can be strings and numbers, as well as arrays (hobbies) and nested documents. Like JSON, this lets you represent related data without splitting it across multiple tables as you might in MySQL.
  • You do not need to declare fields in advance. To add an email field to the next document, simply include it.

This storage format closely matches the JSON used in everyday frontend development, which is one reason frontend developers often find MongoDB easy to learn.


⚖️ Comparing MongoDB and MySQL

If you already know MySQL, these corresponding concepts can help you get started:

MySQLMongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField

A collection contains documents, just as a table contains rows. The difference is that MySQL requires rows in a table to follow the same column structure, defined with CREATE TABLE, whereas a MongoDB collection does not require identical document structures. Fields are determined when you insert data.

When should you use each one? Here is a simple starting point:

  • For stable data structures with closely related tables, such as orders and products, a relational database like MySQL is a good fit.
  • For flexible data structures and rapid iteration, such as content whose fields change frequently, MongoDB's approach of storing JSON-like documents without creating tables can be convenient.
Neither is universally better. Many projects use both: MySQL for core business data, and MongoDB for logs or configuration with variable structures. Understand their characteristics and choose based on your use case.

🛠 Running MongoDB with Docker

As in the MySQL course, we will use Docker to avoid a lengthy local setup. This article was written and tested with MongoDB 8.0 (the mongo:8 Docker image). Make sure Docker is installed before continuing.

Run this command to start a MongoDB container:

docker run -d --name mongo-demo -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=123456 mongo:8

Here is what each option does:

  • -d: Runs the container in the background, leaving your terminal available.
  • --name mongo-demo: Names the container so you can refer to it later.
  • -p 27017:27017: Maps local port 27017 to port 27017 in the container, MongoDB's default port.
  • -e MONGO_INITDB_ROOT_USERNAME=root: Sets the administrator username to root.
  • -e MONGO_INITDB_ROOT_PASSWORD=123456: Sets the administrator password to 123456.
  • mongo:8: Uses version 8.x of the mongo image.

The first run downloads the image, which may take a moment. Once it starts, check that the container is running:

docker ps

If mongo-demo appears with an Up status, MongoDB is running.

These credentials are for local learning only. Use a strong password in a real project. The credentials supplied with -e apply only during initial initialization; changing these environment variables later does not change the existing password.

✨ Connecting with mongosh and Running Your First Command

mongosh is MongoDB's official command-line client and is included in the mongo:8 image. Use it to connect to the container:

docker exec -it mongo-demo mongosh -u root -p 123456 --authenticationDatabase admin
  • docker exec -it mongo-demo: Runs a command interactively inside the mongo-demo container.
  • -u root -p 123456: Authenticates with the credentials you configured.
  • --authenticationDatabase admin: Specifies the system database that stores the account. The root account initialized by the Docker image belongs to admin, so you must specify it when connecting.

The test> prompt indicates that you are connected. mongosh accepts JavaScript-style commands. Start by listing the databases:

show dbs

You will see built-in databases such as admin, config, and local, which MongoDB uses internally. There is no blog_demo yet, and that is fine: you do not need to create a database in advance. MongoDB creates it when you first write data.

Switch to the blog_demo database:

use blog_demo

Next, insert a document into the user collection. You do not need to create the collection first either:

db.user.insertOne({ username: 'Xiao Ming', age: 20, city: 'Beijing' })

The result includes acknowledged: true and an automatically generated insertedId, confirming the insert. Now retrieve the document:

db.user.find()

You should see the document you inserted, including its automatically generated _id. You have completed a full write → read cycle.

If you prefer a graphical interface, try the official MongoDB Compass application with mongodb://root:123456@localhost:27017/?authSource=admin. Both interfaces work; this course uses mongosh throughout.

❓ Questions and Answers

Q1: Without tables, how do I keep document structures consistent?

Your code takes responsibility for consistency. If your Node.js code writes consistent fields, your data stays organized. Later, Mongoose will let you define structural constraints in code, combining flexibility with clear rules.

Q2: Why is blog_demo missing from show dbs after I used it?

Empty databases do not appear in the list. use blog_demo only selects the database; after you insert data, run show dbs again to see it.

Q3: Why do I need --authenticationDatabase admin?

MongoDB accounts belong to a specific database. The Docker image creates the root account in the admin system database, so mongosh must check the credentials there. Otherwise, authentication fails.

Q4: What is db, and why do commands start with it?

db is a built-in mongosh variable representing the current database, selected with use. db.user refers to the user collection in that database.

Q5: Will restarting the container delete my data?

No. Container files remain for the lifetime of the container, so data survives docker stop followed by docker start. Removing the container with docker rm deletes that data, which is usually acceptable for these learning examples.


🧪 Exercises

Exercise 1: In mongosh, insert another document into user. Choose any username, and use your own age and city.

// Write your code here

Exercise 2: Retrieve all documents with db.user.find(). How many documents are there? Does each have the same _id?

// Write your code here

🎉 You have MongoDB running locally and have completed your first write and read! Next, we will cover CRUD operations systematically, including common uses of insert, find, update, and delete.