Learning MongoDB from Scratch: From Installation to Creating the First Database

1. What is MongoDB?

MongoDB is a document - oriented database. Unlike traditional relational databases (such as MySQL) that store data in tables, it stores information using JSON - like “documents” (in BSON format). This approach is more beginner - friendly—you don’t need to remember complex SQL syntax; you can easily manage data with a familiar key - value pair structure.

2. Why Choose MongoDB?

  1. Intuitive and Easy to Understand: Data is stored in “documents”, and each document can have different fields (key - value pairs). It is suitable for flexible and changeable data structures (for example, one user’s information may have “name” and “age”, while another user may have an additional “hobbies” field).
  2. Easy to Get Started: There is no need to design a strict table structure in advance. Collections (similar to tables) are automatically created when inserting data, which is suitable for rapid development.
  3. Cross - platform Support: It can be installed on Windows, macOS, and Linux, and the community documentation is rich.

3. Installing MongoDB (Taking Common Systems as Examples)

Ensure your computer is connected to the internet before installation. The following are the installation steps for different systems:

1. Installation on Windows

  • Step 1: Download the installation package from the MongoDB official website (Click to Download), select the “Windows” version, and follow the prompts to install (be sure to check “Add MongoDB to PATH” for easy command - line operations later).
  • Step 2: Verify the installation success: Open the command prompt (Win + R → enter cmd), and enter mongod --version. If the version number is displayed, the installation is successful.
  • Step 3: Start the MongoDB service: Enter mongod --dbpath=Data Storage Path in the command line (for example, mongod --dbpath=C:\data\db). If C:\data\db does not exist, you need to create the folder manually. After the service starts, a prompt like “waiting for connections on port 27017” will be displayed.

2. Installation on macOS

It is recommended to install using Homebrew (simpler):
- Step 1: Open the terminal and enter brew tap mongodb/brew (add the MongoDB repository).
- Step 2: Enter brew install mongodb - community (install the community version).
- Step 3: Start the service: Use brew services list to check the status of MongoDB. If it is not started, enter brew services start mongodb - community.
- Step 4: Verify the installation: Enter mongo --version to check the version.

3. Installation on Linux (Taking Ubuntu as an Example)

  • Step 1: Open the terminal and execute:
  sudo apt update
  sudo apt install -y mongodb
  • Step 2: Start the service: sudo systemctl start mongod (the default service name in Ubuntu is mongod).
  • Step 3: Verify the installation: Enter mongo --version to check the version.

4. Basic Concepts of MongoDB (Quick Understanding)

  • Database: A container for storing multiple collections, similar to a “folder”.
  • Collection: A container for storing a set of documents, similar to a “table”. It does not need to be created in advance and is automatically generated when data is inserted.
  • Document: The smallest data unit of MongoDB, stored in BSON (binary JSON) format. The field names are unique, and the key - value pairs are flexible (for example: {"name": "Alice", "age": 18, "hobbies": ["reading", "sports"]}).

5. Connecting to MongoDB (Entering the Command - Line Interface)

After installing and starting the MongoDB service, open a new terminal window and enter mongo to enter the MongoDB command - line interface (Mongo Shell), which is the “console” for our database operations.

After successful connection, you will see a prompt similar to the following:

MongoDB shell version v6.0.5
connecting to: mongosh "mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.9.1"
...
> 

(The > is the command prompt of the Mongo Shell, and all subsequent operations are executed here.)

6. Creating the First Database: school

In MongoDB, a database does not need to be “explicitly created”—as long as you select a non - existent database (through the use command), MongoDB will automatically create it.

Step 1: Switch to the school database

Enter the following in the Mongo Shell:

use school

After execution, it will display: switched to db school. At this time, the “school” database has been created (even if you have not inserted any data yet).

Step 2: Create a Collection (students) and Insert Data

Collections (Collections) are “tables” in the database and do not need to be defined in advance. Let’s first create a collection named students and insert a few pieces of student information:

// Insert a single document (student Alice)
db.students.insertOne({
  name: "Alice",
  age: 18,
  gender: "female",
  hobbies: ["reading", "painting"]
})

// Insert multiple documents (students Bob and Charlie)
db.students.insertMany([
  { name: "Bob", age: 19, gender: "male", hobbies: ["basketball", "coding"] },
  { name: "Charlie", age: 17, gender: "male", hobbies: ["gaming", "hiking"] }
])
  • insertOne: Inserts a single document and returns the insertion result (including _id, the unique ID automatically generated by MongoDB).
  • insertMany: Inserts multiple documents and returns an array containing all insertion results.

Step 3: Query Data in the Database

After inserting the data, use the find() method to query all documents in the students collection:

// Query all students (toArray() converts the result into an array for easy viewing)
db.students.find().toArray()

After execution, it will return a result similar to the following (the _id is an automatically generated unique identifier):

[
  {
    "_id": ObjectId("64d5..."),
    "name": "Alice",
    "age": 18,
    "gender": "female",
    "hobbies": ["reading", "painting"]
  },
  {
    "_id": ObjectId("64d5..."),
    "name": "Bob",
    "age": 19,
    "gender": "male",
    "hobbies": ["basketball", "coding"]
  },
  {
    "_id": ObjectId("64d5..."),
    "name": "Charlie",
    "age": 17,
    "gender": "male",
    "hobbies": ["gaming", "hiking"]
  }
]

7. Summary and Next Steps

Congratulations! You have completed the installation of MongoDB, created your first database (school) and collection (students), and also inserted and queried data.

The core features of MongoDB are flexible document structure and no need to predefine table structure, which are suitable for rapid development. Next, you can try:
- Use updateOne() to update a student’s age (for example: db.students.updateOne({name: "Alice"}, {$set: {age: 19}})).
- Use deleteOne() to delete a student (for example: db.students.deleteOne({name: "Charlie"})).

For in - depth learning, you can refer to the MongoDB official documentation, or try using MongoDB to store more complex scenarios (such as blog systems, user data, etc.).

Small Tip: If the MongoDB service is unexpectedly closed, simply enter mongod in the terminal again (Windows needs to ensure the mongod path is correct) to restart the service.

Xiaoye