MongoDB Cheatsheet
A quick guide to MongoDB basics with examples. Learn how to work with databases, collections, queries, and aggregation in an easy-to-understand way.
What is MongoDB?
MongoDB is a NoSQL database that stores data in JSON-like documents. Unlike SQL databases, it doesn’t use tables and rows, but instead collections and documents.
Databases & Collections
A database holds collections, and collections hold documents (similar to rows). Think of documents as JSON objects.
use myDatabase
db.createCollection("users")
CRUD Operations
CRUD means Create, Read, Update, and Delete. These are the basic operations to manage data in MongoDB.
// Create
db.users.insertOne({ name: "Alice", age: 25 })
// Read
db.users.find({ age: 25 })
// Update
db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } })
// Delete
db.users.deleteOne({ name: "Alice" })
Find Queries
The find()
method retrieves documents. You can use filters to match fields and projections to choose which fields to return.
db.users.find({ age: { $gt: 20 } }, { name: 1, _id: 0 })
Comparison & Logical Operators
MongoDB has operators like $gt
(greater than), $lt
(less than), $and
, and $or
to build powerful queries.
db.users.find({ $or: [ { age: { $lt: 18 } }, { age: { $gt: 60 } } ] })
Sorting & Limiting
Use sort()
to order results and limit()
to restrict the number of documents returned.
db.users.find().sort({ age: -1 }).limit(5)
Indexes
Indexes speed up queries. Without them, MongoDB scans every document. You can add indexes to frequently queried fields.
db.users.createIndex({ name: 1 })
Aggregation Framework
Aggregation processes data in stages (like a pipeline). Common stages are $match
(filter), $group
(grouping), and $sort
.
db.users.aggregate([
{ $match: { age: { $gt: 18 } } },
{ $group: { _id: "$city", total: { $sum: 1 } } },
{ $sort: { total: -1 } }
])
Relationships
MongoDB supports embedding (store related data in one document) or referencing (link documents with IDs). Embedding is faster, while referencing is more flexible.
// Embedding
{
name: "Alice",
orders: [ { product: "Book", price: 10 } ]
}
// Referencing
{
name: "Alice",
orders: [ObjectId("order_id_here")]
}
How to use this page
- Start with databases and collections basics.
- Practice CRUD operations on documents.
- Explore queries, sorting, and operators.
- Learn about indexes and aggregation for performance.
🚀 Explore More Free Developer Tools
Don’t stop here! Supercharge your workflow with our other powerful converters & formatters.
📚 Next.js Cheatsheet
Next.js Cheatsheet
📚 SCSS Cheatsheet
SCSS Cheatsheet
📚 SQL Cheatsheet
SQL Cheatsheet
💡 New tools are added regularly — bookmark DevUtilsX and stay ahead!
Want to support my work?
Buy me a coffee