Skip to content

MongoDB - Cheatsheet

This cheatsheet provides a quick reference for essential MongoDB commands and concepts, updated for modern development practices. MongoDB is a leading NoSQL, document-oriented database, ideal for scalable and flexible web applications.

Install MongoDB Community Edition via package managers or use Docker for a portable setup.

# macOS (using Homebrew)
brew tap mongodb/brew
brew install mongodb-community
# Ubuntu (using apt)
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
# Docker (Recommended for dev)
docker run -d -p 27017:27017 --name my-mongo mongo

Connect using the MongoDB Shell (mongosh):

mongosh
  • Switch/Create Database: use myNewDB (Database is created on first data insertion)
  • Show Current Database: db
  • List All Databases: show dbs
  • Create Collection (Explicitly): db.createCollection("users")
  • Show Collections: show collections
  • Drop Current Database: db.dropDatabase()
  • Drop a Collection: db.users.drop()
// Insert a single document
db.users.insertOne({ name: "Alice", age: 30, city: "New York" })
// Insert multiple documents
db.users.insertMany([
{ name: "Bob", age: 25, city: "Paris" },
{ name: "Charlie", age: 35, city: "Tokyo" }
])
// Find all documents
db.users.find()
// Find with a filter
db.users.find({ city: "New York" })
// Find one document
db.users.findOne({ name: "Alice" })
// Update the first matching document
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 31 }, $currentDate: { lastModified: true } }
)
// Update all matching documents
db.users.updateMany(
{ city: "New York" },
{ $inc: { bonusPoints: 10 } }
)
// Replace a document
db.users.replaceOne({ name: "Bob" }, { name: "Robert", age: 25, city: "Paris" })
// Delete the first matching document
db.users.deleteOne({ name: "Charlie" })
// Delete all matching documents
db.users.deleteMany({ age: { $lt: 20 } })
  • Comparison: $eq (equal), $ne (not equal), $gt (greater than), $gte (>=), $lt (less than), $lte (<=), $in (in an array), $nin (not in an array)
  • Logical: $and, $or, $not, $nor
  • Element: $exists (field exists), $type (field is of a certain BSON type)
  • Array: $all (match all elements), $size (array is a specific size), $elemMatch (match an element in an array)
// Find users older than 30 OR from Tokyo
db.users.find({ $or: [ { age: { $gt: 30 } }, { city: "Tokyo" } ] })
// Find users who have a 'zipcode' field
db.users.find({ zipcode: { $exists: true } })

Modify the output of a find() query.

// Sort by age descending, limit to 5 results, skip the first 2
db.users.find().sort({ age: -1 }).limit(5).skip(2)
// Count documents matching a query
db.users.countDocuments({ city: "Paris" })
// Get distinct values for a field
db.users.distinct("city")
// Create a single-field index (ascending)
db.users.createIndex({ name: 1 })
// Create a compound index
db.users.createIndex({ city: 1, age: -1 })
// Create a unique index
db.users.createIndex({ email: 1 }, { unique: true })
// Create a text index for text search
db.articles.createIndex({ content: "text" })
// List all indexes on a collection
db.users.getIndexes()
// Drop a specific index
db.users.dropIndex("name_1")

Process data records and return computed results. It’s a pipeline of stages.

// Group users by city and calculate the average age per city
db.users.aggregate([
{ $match: { age: { $gte: 20 } } }, // Stage 1: Filter documents
{
$group: { // Stage 2: Group by city
_id: "$city",
averageAge: { $avg: "$age" },
userCount: { $sum: 1 }
}
},
{ $sort: { userCount: -1 } } // Stage 3: Sort by count
])
  • Transactions: For multi-document ACID transactions. Requires a replica set.
  • Change Streams: A real-time stream of data changes (inserts, updates, deletes).
  • Query Analysis: db.collection.explain('executionStats') to see how a query performs.
  • MongoDB Atlas: The official cloud-hosted MongoDB service, simplifying deployment, scaling, and management.
// Example of a transaction
const session = db.getMongo().startSession();
session.startTransaction();
const users = session.getDatabase("myDB").getCollection("users");
const audit = session.getDatabase("myDB").getCollection("audit");
users.updateOne({ name: "Alice" }, { $inc: { balance: -100 } });
audit.insertOne({ user: "Alice", action: "debit", amount: 100 });
session.commitTransaction();
session.endSession();