Introduction
MongoDB is a popular NoSQL database known for its flexible document-based model, scalability, and powerful querying capabilities. Whether you are a beginner or an experienced developer, this comprehensive guide and cheatsheet will serve as a one-stop solution for mastering MongoDB.
1. Key MongoDB Concepts
Concept | Description |
---|---|
Database | A container for collections. |
Collection | A group of documents (similar to a table in RDBMS). |
Document | A JSON-like object (key-value pairs, dynamic schema). |
Field | A key-value pair in a document. |
Index | Improves the speed of data retrieval. |
Aggregation | Used for complex data processing and transformation. |
Replication | Copies data across multiple servers for fault tolerance. |
Sharding | Splits data across multiple servers to handle large datasets. |
2. Setting Up MongoDB
Installation
-
Windows / Linux / macOS:
- Download from MongoDB Official Site.
- Follow installation instructions.
- Start the service:
mongod
Mongo Shell Access:
mongosh
3. Basic MongoDB Commands
Database Operations
Command | Description |
---|---|
show dbs |
List all databases. |
use <database> |
Switch to a database. |
db.createCollection('users') |
Create a collection. |
db.dropDatabase() |
Drop the current database. |
Collection Operations
Command | Description |
---|---|
db.users.insertOne({...}) |
Insert a single document. |
db.users.insertMany([{...}, {...}]) |
Insert multiple documents. |
db.users.find() |
Fetch all documents. |
db.users.find({name: "John"}) |
Query documents with conditions. |
db.users.updateOne({condition}, {$set: {key: value}}) |
Update a document. |
db.users.deleteOne({name: "John"}) |
Delete a single document. |
db.users.deleteMany({age: {$gt: 30}}) |
Delete multiple documents. |
4. Advanced Querying
Query | Description |
---|---|
$gt , $lt , $gte , $lte
|
Comparison operators (greater, less, etc.) |
$in , $nin
|
Matches values in a set. |
$and , $or , $not
|
Logical operators. |
$exists , $type
|
Field existence and type check. |
$regex |
Pattern matching. |
Example:
db.users.find({
$and: [
{ age: { $gte: 25 } },
{ city: "New York" }
]
});
5. Aggregation Framework
Used for advanced data analysis and processing.
Stage | Description |
---|---|
$match |
Filters documents. |
$group |
Groups documents by a field. |
$sort |
Sorts documents. |
$limit |
Limits the number of documents. |
$project |
Reshapes documents. |
Example:
db.sales.aggregate([
{ $match: { status: "Completed" } },
{ $group: { _id: "$product", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
]);
6. Indexing
Type | Description |
---|---|
Single Field Index | Index on a single field. |
Compound Index | Index on multiple fields. |
Text Index | Full-text search support. |
Create Index:
db.users.createIndex({ name: 1 });
7. Relationships in MongoDB
Approach | Description |
---|---|
Embedded Documents | Store related data in a single document. |
References | Store references (ObjectId) to other documents. |
Embedded Example:
{
name: "John Doe",
address: {
city: "New York",
zip: "10001"
}
}
Reference Example:
{
name: "John Doe",
addressId: ObjectId("603cf82a5e8b7a2e9c1f1f1f")
}
8. Data Modeling Best Practices
- Design according to application query patterns.
- Favor embedded documents for fast reads.
- Use references for complex relationships or large datasets.
- Index frequently queried fields.
9. Backup and Restore
Command | Description |
---|---|
mongodump --out /backup |
Backup all databases. |
mongorestore /backup |
Restore from backup. |
10. MongoDB Compass (GUI Tool)
- Download: MongoDB Compass
- Connect using connection string.
- Visualize data and perform queries.
11. Performance Optimization Tips
- Use proper indexing.
- Avoid
$where
and complex JavaScript operations. - Limit the result set using
.limit()
and.skip()
. - Use aggregation pipelines for heavy data processing.
12. Common Errors & Solutions
Error | Cause/ Solution |
---|---|
E11000 duplicate key error |
Unique index conflict, check for duplicates. |
Network Error |
Check server connection or firewall. |
MongoParseError |
Invalid connection string format. |
13. Quick MongoDB Cheatsheet
// Database Operations
show dbs;
use mydb;
db.dropDatabase();
// Collection Operations
db.createCollection('users');
db.users.drop();
// CRUD Operations
db.users.insertOne({name: "Alice", age: 25});
db.users.find({age: {$gte: 25}});
db.users.updateOne({name: "Alice"}, {$set: {age: 26}});
db.users.deleteOne({name: "Alice"});
// Aggregation
db.users.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: { _id: "$city", count: { $sum: 1 } } }
]);
// Indexing
db.users.createIndex({name: 1});
db.users.getIndexes();
// Backup & Restore
mongodump --out /backup;
mongorestore /backup;
14. Useful Resources
Final Thoughts
Mastering MongoDB involves understanding its flexible document model, using aggregation for powerful data analysis, and optimizing performance with indexing. With this guide and cheatsheet, you’re equipped to handle MongoDB confidently in your development projects.
Happy Coding!
Top comments (0)