MongoDB - Cheatsheet
MongoDB Modern Cheatsheet
Section titled “MongoDB Modern 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.
1. Installation and Setup
Section titled “1. Installation and Setup”Install MongoDB Community Edition via package managers or use Docker for a portable setup.
# macOS (using Homebrew)brew tap mongodb/brewbrew 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.listsudo apt-get updatesudo apt-get install -y mongodb-org
# Docker (Recommended for dev)docker run -d -p 27017:27017 --name my-mongo mongoConnect using the MongoDB Shell (mongosh):
mongosh2. Database and Collection Commands
Section titled “2. Database and Collection Commands”- 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()
3. CRUD Operations
Section titled “3. CRUD Operations”Create (Insert)
Section titled “Create (Insert)”// Insert a single documentdb.users.insertOne({ name: "Alice", age: 30, city: "New York" })
// Insert multiple documentsdb.users.insertMany([ { name: "Bob", age: 25, city: "Paris" }, { name: "Charlie", age: 35, city: "Tokyo" }])Read (Find)
Section titled “Read (Find)”// Find all documentsdb.users.find()
// Find with a filterdb.users.find({ city: "New York" })
// Find one documentdb.users.findOne({ name: "Alice" })Update
Section titled “Update”// Update the first matching documentdb.users.updateOne( { name: "Alice" }, { $set: { age: 31 }, $currentDate: { lastModified: true } })
// Update all matching documentsdb.users.updateMany( { city: "New York" }, { $inc: { bonusPoints: 10 } })
// Replace a documentdb.users.replaceOne({ name: "Bob" }, { name: "Robert", age: 25, city: "Paris" })Delete
Section titled “Delete”// Delete the first matching documentdb.users.deleteOne({ name: "Charlie" })
// Delete all matching documentsdb.users.deleteMany({ age: { $lt: 20 } })4. Query Operators
Section titled “4. Query Operators”- 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 Tokyodb.users.find({ $or: [ { age: { $gt: 30 } }, { city: "Tokyo" } ] })
// Find users who have a 'zipcode' fielddb.users.find({ zipcode: { $exists: true } })5. Query Cursors
Section titled “5. Query Cursors”Modify the output of a find() query.
// Sort by age descending, limit to 5 results, skip the first 2db.users.find().sort({ age: -1 }).limit(5).skip(2)
// Count documents matching a querydb.users.countDocuments({ city: "Paris" })
// Get distinct values for a fielddb.users.distinct("city")6. Indexing
Section titled “6. Indexing”// Create a single-field index (ascending)db.users.createIndex({ name: 1 })
// Create a compound indexdb.users.createIndex({ city: 1, age: -1 })
// Create a unique indexdb.users.createIndex({ email: 1 }, { unique: true })
// Create a text index for text searchdb.articles.createIndex({ content: "text" })
// List all indexes on a collectiondb.users.getIndexes()
// Drop a specific indexdb.users.dropIndex("name_1")7. Aggregation Framework
Section titled “7. Aggregation Framework”Process data records and return computed results. It’s a pipeline of stages.
// Group users by city and calculate the average age per citydb.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])8. Advanced Topics
Section titled “8. Advanced Topics”- 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 transactionconst 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();