MongoDB is a popular non-relational database (NoSQL database) that stores data in document form with flexible structures and easy scalability. It is ideal for rapid development and handling large volumes of unstructured or semi-structured data. For beginners, MongoDB has a relatively gentle learning curve. Today, we’ll start from the most basic concepts and operations to gradually explore the world of MongoDB.
一、What is MongoDB?¶
In simple terms, MongoDB is a distributed file storage-based database. Unlike MySQL, which uses “tables” to store data, MongoDB uses “documents” (key-value pairs in a JSON-like format) to store data. Multiple documents are organized into a “collection” (similar to a “table” in MySQL), and multiple collections belong to a “database”.
For example, if MySQL is compared to a “table factory” (each row is a record, each column is a field), MongoDB is like a “building block warehouse” — you can freely combine different “building blocks” (fields) to flexibly construct the required data structure.
二、Installing MongoDB¶
1. Local Installation (Recommended)¶
-
Windows System:
Download the installer from the MongoDB official website (https://www.mongodb.com/try/download/community), select the appropriate version (64-bit is recommended), and follow the prompts to install. Remember to check “Add to PATH” during installation for easy command-line access. After installation, open the Command Prompt (CMD) and runmongod --versionto verify success. -
Linux System (Ubuntu example):
Open the terminal and execute:
sudo apt update && sudo apt install -y mongodb
Start the service: sudo systemctl start mongod, and set it to start on boot: sudo systemctl enable mongod.
- Mac System:
Recommended to use Homebrew:brew tap mongodb/brew && brew install mongodb-community. Check the status withbrew services list | grep mongodb-community. If not running, start it withbrew services start mongodb-community.
2. Verify Installation¶
After installation, open a new terminal/command-line window and run mongo to connect to the local MongoDB service (default port 27017). If you see a prompt like >, the connection is successful!
三、Basic Command-Line Operations in MongoDB¶
MongoDB’s core interaction method is the command-line tool (mongo shell). We’ll start with basic database, collection, and document operations.
1. Database Operations¶
-
Switch/Create Database:
There is no explicit “create database” command in MongoDB. Simply useuse 数据库名(e.g.,use mydb). If the database does not exist, it will be automatically created, and subsequent operations will be associated with this database. -
View All Databases:
Runshow dbs(note: empty databases are not displayed; only databases with data are listed). -
View Current Database:
Enterdbto display the name of the currently selected database (e.g., the newly created “mydb”). -
Delete Database:
First switch to the target database (use mydb), then executedb.dropDatabase(), which will return{ "dropped" : "mydb", "ok" : 1 }indicating success.
2. Collection Operations (Collection)¶
A collection is equivalent to a “table” in a relational database, a set of documents. Collections in MongoDB do not need explicit creation; they are automatically created when documents are inserted (but can also be explicitly created with createCollection).
-
View Collections:
After switching to the target database, runshow collectionsorshow tables(both work) to list all collections in the database. -
Delete Collection:
Switch to the target database and executedb.集合名.drop(), e.g.,db.students.drop(), which returnstrueif successful.
3. Document Operations (Document)¶
A document is the smallest data unit in MongoDB, formatted as JSON (key-value pairs) with support for nested structures, making it highly flexible. We focus on Create, Read, Update, Delete (CRUD) operations.
(1) Insert Document (Create)¶
Use insertOne (single document) or insertMany (multiple documents).
Example: Insert a single student document
db.students.insertOne({
name: "小明",
age: 18,
hobbies: ["篮球", "编程"], // Array type
address: { city: "北京", district: "海淀区" } // Nested document
})
Return result:
{
"acknowledged" : true,
"insertedId" : ObjectId("60d21b4660d21b4660d21b46"), // Auto-generated unique ID
"ok" : 1
}
Insert multiple documents:
db.students.insertMany([
{ name: "小红", age: 19, hobbies: ["画画", "音乐"] },
{ name: "小刚", age: 20, hobbies: ["跑步", "游戏"] }
])
(2) Query Document (Read)¶
Use find() to query, which returns all documents in the collection by default (similar to MySQL’s SELECT * FROM).
- Query all documents:
db.students.find() // Returns a cursor; use it for iteration
If the result set is large, the cursor shows the first 20 documents by default. Use it to iterate through remaining results or toArray() to convert to an array:
db.students.find().toArray() // Returns an array of all student data
- Query with conditions:
Usefind({condition}). For example, query students with age 18:
db.students.find({ age: 18 })
Common condition operators: $gt (greater than), $lt (less than), $eq (equal, optional), $in (inclusion), etc.
Example: Query students aged 18 to 20:
db.students.find({ age: { $gt: 18, $lt: 20 } })
(3) Update Document (Update)¶
Use updateOne (update one document) or updateMany (update multiple documents), specifying a filter condition and update content.
- Basic update (replace document):
Use$setto modify specific fields or directly replace the entire document.
Example: Update “小明”’s age to 20:
db.students.updateOne(
{ name: "小明" }, // Filter: name is "小明"
{ $set: { age: 20 } } // Update: only modify the "age" field
)
Return result:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
- Incremental update:
Use$incto increment numeric fields (e.g., age+1):
db.students.updateOne({ name: "小红" }, { $inc: { age: 1 } }) // age increases by 1
(4) Delete Document (Delete)¶
Use deleteOne (delete one document) or deleteMany (delete multiple documents).
- Delete one document:
db.students.deleteOne({ name: "小刚" }) // Delete the first document with name "小刚"
- Delete multiple documents:
db.students.deleteMany({ age: { $lt: 19 } }) // Delete all students under 19
四、Graphical Tool: MongoDB Compass¶
Command-line operations are suitable for programming, but graphical tools are more intuitive for daily data management. We recommend the official tool MongoDB Compass.
1. Installation and Connection¶
- Download the installer from the official website: https://www.mongodb.com/products/compass
- After installation, open Compass and click “Connect”. By default, it connects to the local MongoDB at
mongodb://localhost:27017. Click “Connect” to proceed.
2. Tool Features¶
- View Databases/Collections: The left navigation bar lists all databases and collections. Click a collection to view all documents.
- CRUD Operations: Select a collection, then input JSON-formatted documents on the right (for insertion), or use “Edit” to modify/ “Delete” to remove documents.
- Search and Filter: Use the top search bar to filter documents by conditions (similar to the command-line
find()).
五、Summary and Learning Suggestions¶
MongoDB’s core advantages are its flexible document structure and no fixed table schema, making it suitable for projects with rapid iteration. For beginners, we recommend:
- Practice Hands-On: Start with simple insert/query operations on the command line to familiarize yourself with CRUD operations.
- Compare with Relational Databases: Understand the mappings: “collection → table”, “document → row” to reduce cognitive load.
- Focus on Nested Documents: MongoDB supports multi-level nested documents, which is key for handling complex data (e.g., user info + address + orders).
For advanced learning, explore indexes (createIndex), aggregation pipelines (aggregate), replica sets, etc. But master the basics first! MongoDB is beginner-friendly — practice commands and experiments, and happy learning!