MongoDB is the leading NoSQL database. This comprehensive guide will take you from complete beginner to confident MongoDB user.
What is MongoDB?
MongoDB is a document-based NoSQL database that stores data in flexible, JSON-like documents instead of traditional tables with rows and columns.
Core Concepts
- Database: Container for collections
- Collection: Group of documents (like tables in SQL)
- Document: Set of key-value pairs (like rows)
- Field: Name-value pair (like columns)
Installation and Setup
# Install MongoDB Community Edition (Ubuntu/Debian)
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
# Start MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod
# Connect to MongoDB
mongosh
Basic CRUD Operations
Create (Insert)
// Insert one document
db.users.insertOne({
name: "Mohamed Saber",
email: "mohamed@example.com",
age: 28,
skills: ["React", "Node.js", "MongoDB"]
})
// Insert multiple documents
db.users.insertMany([
{ name: "Ahmed", email: "ahmed@example.com", age: 25 },
{ name: "Sara", email: "sara@example.com", age: 30 }
])
Read (Query)
// Find all documents
db.users.find()
// Find with condition
db.users.find({ age: { $gt: 25 } })
// Find one document
db.users.findOne({ email: "mohamed@example.com" })
// Projection (select specific fields)
db.users.find({}, { name: 1, email: 1, _id: 0 })
Update
// Update one document
db.users.updateOne(
{ email: "mohamed@example.com" },
{ $set: { age: 29 } }
)
// Update multiple documents
db.users.updateMany(
{ age: { $lt: 25 } },
{ $set: { status: "junior" } }
)
// Replace document
db.users.replaceOne(
{ email: "ahmed@example.com" },
{ name: "Ahmed Ali", email: "ahmed.ali@example.com", age: 26 }
)
Delete
// Delete one document
db.users.deleteOne({ email: "ahmed@example.com" })
// Delete multiple documents
db.users.deleteMany({ age: { $lt: 18 } })
// Delete all documents
db.users.deleteMany({})
Query Operators
// Comparison operators
db.users.find({ age: { $eq: 28 } }) // Equal
db.users.find({ age: { $ne: 28 } }) // Not equal
db.users.find({ age: { $gt: 25 } }) // Greater than
db.users.find({ age: { $gte: 25 } }) // Greater than or equal
db.users.find({ age: { $lt: 30 } }) // Less than
db.users.find({ age: { $lte: 30 } }) // Less than or equal
db.users.find({ age: { $in: [25, 28, 30] } }) // In array
// Logical operators
db.users.find({ $and: [{ age: { $gt: 25 } }, { age: { $lt: 30 } }] })
db.users.find({ $or: [{ age: 25 }, { age: 28 }] })
db.users.find({ $nor: [{ age: 25 }, { age: 28 }] })
db.users.find({ $not: { age: { $gt: 25 } } })
// Element operators
db.users.find({ email: { $exists: true } })
db.users.find({ age: { $type: "number" } })
Indexing for Performance
// Create single field index
db.users.createIndex({ email: 1 })
// Create compound index
db.users.createIndex({ age: 1, name: 1 })
// Create text index for search
db.users.createIndex({ name: "text", description: "text" })
// List indexes
db.users.getIndexes()
// Drop index
db.users.dropIndex("email_1")
Aggregation Pipeline
// Basic aggregation
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 10 }
])
// Lookup (join) example
db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}
},
{ $unwind: "$user" }
])
Working with Mongoose (Node.js ODM)
// Schema definition
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 0, max: 120 },
skills: [String],
createdAt: { type: Date, default: Date.now }
}, { timestamps: true });
// Model
const User = mongoose.model('User', userSchema);
// CRUD with Mongoose
const newUser = await User.create({ name: "Mohamed", email: "mohamed@example.com" });
const users = await User.find({ age: { $gte: 18 } }).sort({ name: 1 });
const updated = await User.findByIdAndUpdate(id, { age: 29 }, { new: true });
const deleted = await User.findByIdAndDelete(id);
Best Practices
- Always use indexes on fields used in queries
- Use projection to limit returned fields
- Implement proper validation at application level
- Use transactions for multi-document operations when needed
- Monitor and optimize slow queries
- Enable authentication and authorization
- Regular backups using mongodump
- Use connection pooling in production
MongoDB Atlas (Cloud)
MongoDB Atlas is the official cloud service offering:
- Free tier with 512MB storage
- Automated backups
- Global clusters
- Performance advisor
- Built-in monitoring
Conclusion
MongoDB's flexible schema, powerful query language, and scalability make it an excellent choice for modern applications. Start with simple CRUD operations, experiment with aggregation pipelines, and always consider performance optimization through proper indexing.

