MongoDB
Updated: September 10, 2025Categories: Query, Backend, NoSQL
Printed from:
MongoDB Query Language (MQL) Cheatsheet
1. Connection and Basic Commands
Connecting to MongoDB
Bash
123456789# Connect to local MongoDB instance
mongo
# Connect to remote MongoDB instance
mongo "mongodb://username:password@host:port/database"
# Connect using MongoDB Atlas
mongo "mongodb+srv://cluster.mongodb.net/database" --username username
Basic Shell Commands
JavaScript
123456789// Show all databases
show dbs
// Switch/create database
use myDatabase
// Show collections in current database
show collections
2. Database and Collection Operations
Create and Drop
JavaScript
12345678910111213// Create a database (happens automatically when first used)
use newDatabase
// Create a collection
db.createCollection("users")
// Drop a database
use myDatabase
db.dropDatabase()
// Drop a collection
db.users.drop()
3. Document Structure and BSON Types
Document Example
JavaScript
12345678910111213{
_id: ObjectId("5f8d7a1b9d3b2a1b9c1d2e3f"),
name: "John Doe",
age: 30,
active: true,
tags: ["developer", "mongodb"],
address: {
street: "123 Code Lane",
city: "Techville"
},
createdAt: ISODate("2023-09-09T12:00:00Z")
}
BSON Types
String: Text dataInteger: Whole numbersDouble: Floating-point numbersBoolean: true/falseArray: List of valuesObject: Embedded documentsObjectId: Unique document identifierDate: TimestampNull: Absence of valueTimestamp: Internal MongoDB useBinary: Raw binary dataDecimal128: High-precision decimal
4. CRUD Operations
Insert Documents
JavaScript
12345678910111213// Insert a single document
db.users.insertOne({
name: "Alice",
age: 28,
email: "alice@example.com"
})
// Insert multiple documents
db.users.insertMany([
{ name: "Bob", age: 35 },
{ name: "Charlie", age: 42 }
])
Find Documents
JavaScript
1234567891011121314151617// Find all documents
db.users.find()
// Find with specific criteria
db.users.find({ age: { $gt: 30 } })
// Find specific fields
db.users.find(
{ age: { $gt: 25 } },
{ name: 1, age: 1, _id: 0 }
)
// Limit and sort results
db.users.find()
.limit(5)
.sort({ age: 1 })
Update Documents
JavaScript
123456789101112131415161718// Update a single document
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 29 } }
)
// Update multiple documents
db.users.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 1 } }
)
// Replace entire document
db.users.replaceOne(
{ name: "Bob" },
{ name: "Robert", age: 36 }
)
Delete Documents
JavaScript
123456// Delete a single document
db.users.deleteOne({ name: "Alice" })
// Delete multiple documents
db.users.deleteMany({ age: { $lt: 25 } })
5. Query Operators
Comparison Operators
JavaScript
123456789101112// Equality
db.users.find({ age: { $eq: 30 } })
// Greater than/less than
db.users.find({ age: { $gt: 25, $lt: 40 } })
// In array of values
db.users.find({ status: { $in: ["active", "pending"] } })
// Not equal
db.users.find({ status: { $ne: "inactive" } })
Logical Operators
JavaScript
12345678910111213141516// AND
db.users.find({
$and: [
{ age: { $gt: 25 } },
{ status: "active" }
]
})
// OR
db.users.find({
$or: [
{ age: { $lt: 30 } },
{ status: "VIP" }
]
})
Text and Regex Operators
JavaScript
123456// Text search
db.articles.find({ $text: { $search: "mongodb database" } })
// Regex matching
db.users.find({ name: { $regex: /^John/, $options: 'i' } })
6. Aggregation Framework
Basic Pipeline
JavaScript
123456789101112131415161718db.sales.aggregate([
// Match stage
{ $match: { status: "completed" } },
// Group stage
{ $group: {
_id: "$product",
totalRevenue: { $sum: "$amount" },
avgPrice: { $avg: "$price" }
}},
// Sort stage
{ $sort: { totalRevenue: -1 } },
// Limit stage
{ $limit: 5 }
])
Common Aggregation Stages
$match: Filter documents$group: Group by key and perform calculations$sort: Order results$project: Shape output documents$lookup: Join collections$unwind: Deconstruct array fields
7. Indexing and Performance
Create Indexes
JavaScript
123456789101112// Single field index
db.users.createIndex({ email: 1 })
// Compound index
db.users.createIndex({ lastName: 1, firstName: 1 })
// Unique index
db.users.createIndex({ email: 1 }, { unique: true })
// Text index
db.articles.createIndex({ content: "text" })
Performance Tips
- Use indexes for frequently queried fields
- Avoid large, complex queries
- Use projection to return only needed fields
- Use
explain()to analyze query performance
8. Schema Validation
JavaScript
123456789101112131415161718192021// Create collection with schema validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: {
bsonType: "string",
description: "must be a string"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "must be a valid email"
}
}
}
}
})
9. GridFS for Large Files
JavaScript
123456// Store large files (>16MB)
// Using mongofiles or programmatic approach
const bucket = new GridFSBucket(db);
const uploadStream = bucket.openUploadStream('myfile.txt');
fs.createReadStream('myfile.txt').pipe(uploadStream);
10. Transactions and Consistency
JavaScript
1234567891011121314151617181920212223// Multi-document ACID transaction
const session = db.getMongo().startSession();
session.startTransaction();
try {
const usersCollection = session.getDatabase("mydb").users;
const accountsCollection = session.getDatabase("mydb").accounts;
usersCollection.insertOne({ name: "New User" }, { session });
accountsCollection.updateOne(
{ _id: accountId },
{ $inc: { balance: -100 } },
{ session }
);
session.commitTransaction();
} catch (error) {
session.abortTransaction();
throw error;
} finally {
session.endSession();
}
11. Replication and Sharding Basics
Replication
- Primary node handles writes
- Secondary nodes replicate data
- Provides high availability
- Use replica sets for fault tolerance
Sharding
- Distribute data across multiple machines
- Shard key determines data distribution
- Improves read/write scalability
12. Common Patterns
Embedded vs Referenced Documents
JavaScript
1234567891011121314151617181920// Embedded (denormalized)
{
_id: ObjectId("..."),
name: "Product",
reviews: [
{ user: "Alice", rating: 5 },
{ user: "Bob", rating: 4 }
]
}
// Referenced (normalized)
// users collection
{ _id: ObjectId("alice_id"), name: "Alice" }
// products collection
{
_id: ObjectId("..."),
name: "Product",
reviews: [ObjectId("alice_id"), ObjectId("bob_id")]
}
13. Performance Optimization Tips
- Use appropriate indexes
- Avoid
$whereand complex$regex - Limit result sets
- Use projections
- Denormalize when read-heavy
- Use aggregation for complex computations
- Monitor with
explain() - Use capped collections for time-series data
Additional Resources
- MongoDB Documentation: https://docs.mongodb.com
- MongoDB University: https://university.mongodb.com
- MongoDB Compass: GUI for MongoDB
Note: Always refer to the latest MongoDB documentation for most up-to-date information and best practices.
Continue Learning
Discover more cheatsheets to boost your productivity