What is MongoDB? Simply put, it is a database that “speaks the JSON language”. If you’ve used JSON (such as the data format in JavaScript), understanding MongoDB will be very easy.
1. How is MongoDB different from traditional databases?¶
Traditional databases (like MySQL) are like “table libraries”, where each row of data must strictly correspond to column definitions (e.g., a student table has fixed fields like student ID, name, and class). In contrast, MongoDB is more like an “open warehouse”. Data is stored in the form of “documents”, similar to independent “JSON files”. The structure is flexible—different documents can have different fields, and there’s no need to predefine table structures.
2. The core of MongoDB: JSON-formatted “documents”¶
The basic storage unit of MongoDB is a document, which is essentially a JSON-formatted object. For example, a user information document might look like this:
{
"_id": "123", // MongoDB automatically generates a unique ID
"name": "小明",
"age": 20,
"hobbies": ["读书", "运动"],
"address": {
"city": "北京",
"street": "中关村大街"
}
}
Each document can have its own fields and even nested objects. There’s no need for alignment with other documents in structure.
3. Why is MongoDB so popular? 3 key advantages¶
- High flexibility: You can modify the data structure as needed. For example, if you initially create a user table and later want to add a “phone number” field, you can simply add it to new documents without altering the entire table structure.
- Fast development: It natively supports JSON, seamlessly integrating with front-end and back-end code (especially JavaScript and Node.js). You can directly store JSON data in MongoDB without additional format conversion during coding.
- Easy to scale: If data volume suddenly increases, MongoDB supports “horizontal scaling” (e.g., multiple servers sharing the load), unlike traditional databases that require complex database sharding.
4. Key concepts to know¶
- Collection: Equivalent to a “table” in a traditional database, but it stores multiple documents (e.g., a “user collection” contains multiple user documents).
- Document: The JSON object mentioned earlier. Each document has a unique ID (
_id), automatically generated by MongoDB. - Data types: Supports strings, numbers, booleans, arrays, nested objects, and even binary data—almost identical to JSON.
5. Scenarios suitable for MongoDB¶
- Products with rapid iteration (e.g., App backends where requirements constantly change? MongoDB saves time).
- Semi-structured data (e.g., logs, user behavior, configuration information with non-fixed structures).
- Businesses requiring high flexibility (e.g., e-commerce platforms with diverse product attributes, which MongoDB can easily adapt to).
MongoDB is like a “JSON-friendly player” in the database world. If you need flexible storage and fast development, it is definitely a great choice for entry-level databases.