Complete guide to mastering MongoDB - from basics to advanced operations
MongoDB is a powerful NoSQL document-oriented database that stores data in JSON-like documents (actually BSON - Binary JSON). This handbook uses an e-commerce website as the primary example with three main collections:
Go to https://cloud.mongodb.com and create a free account
Create a free cluster (Serverless recommended for beginners)
Whitelist your IP address and create a database user with credentials
Follow the connection string instructions to connect via mongosh or your application
Design schemas based on how you'll query data, not just how it's structured. Embed related data that's accessed together.
Create indexes on frequently queried fields. Monitor query performance with explain() before adding indexes.
Use projection to return only needed fields. Limit results when possible. Use covered queries with indexes.
Regularly backup your data. Use updateOne/updateMany instead of save(). Always test delete operations with find() first.
Enable authentication. Use role-based access control. Keep MongoDB updated with latest security patches.
Use MongoDB Compass or Atlas for performance monitoring. Watch for slow queries and optimize them with indexes.
| Operation | Command | Example |
|---|---|---|
| Create | insertOne(), insertMany() | db.products.insertOne({name: "Item"}) |
| Read | find(), findOne() | db.products.find({price: {$gt: 100}}) |
| Update | updateOne(), updateMany() | db.products.updateOne({}, {$set: {}}) |
| Delete | deleteOne(), deleteMany() | db.products.deleteMany({status: "old"}) |
| Operator | Description | Example |
|---|---|---|
| $eq | Equal to | {price: {$eq: 100}} |
| $gt / $gte | Greater than / Greater than or equal | {price: {$gte: 100}} |
| $lt / $lte | Less than / Less than or equal | {stock: {$lt: 50}} |
| $in | Match any value in array | {category: {$in: ["A", "B"]}} |
| $or | Logical OR | {$or: [{a: 1}, {b: 2}]} |
| $and | Logical AND | {$and: [{a: 1}, {b: 2}]} |
| Operator | Description | Example |
|---|---|---|
| $set | Set field value | {$set: {price: 100}} |
| $inc | Increment value | {$inc: {stock: 5}} |
| $push | Add to array | {$push: {tags: "new"}} |
| $pull | Remove from array | {$pull: {tags: "old"}} |
| $unset | Remove field | {$unset: {field: ""}} |