MongoDB is a popular NoSQL database that offers flexibility and scalability for managing large volumes of data. Whether you're a beginner or an experienced developer, having a handy reference for MongoDB commands and operations can streamline your workflow. In this article, we'll cover the essential MongoDB commands and operations in a convenient cheat sheet format.
Introduction
MongoDB is a document-oriented database that stores data in flexible, JSON-like documents. It is designed to be scalable, high-performance, and easy to use.
Basic Commands
- Show Databases
Code
show dbs - Switch Database
Code
use databaseName - Show Collections
Code
show collections - Create Collection
Code
db.createCollection("collectionName")
CRUD Operations
- Insert Document
Code
db.collectionName.insertOne({}) db.collectionName.insertMany([{}, {}]) - Find Document
Code
db.collectionName.find({}) db.collectionName.findOne({}) - Update Document
Code
db.collectionName.updateOne({filter}, {$set: {}}) db.collectionName.updateMany({filter}, {$set: {}}) - Find and Update Documents
Code
db.collectionName.findOneAndUpdate({filter}, {$set: {}}) # Find and update a document - Find and Delete Documents
Code
db.collectionName.findOneAndDelete({filter}) - Find and Replace Documents
Code
db.collectionName.findOneAndReplace({filter}, {replacement}) - Bulk Write Operations
Python
db.collectionName.bulkWrite([ { insertOne: { document: { key: "value" } } }, { updateMany: { filter: { key: "value" }, update: { $set: { key: "newValue" } } } }, { deleteOne: { filter: { key: "value" } } } ]) - Delete Document
Code
db.collectionName.deleteOne({filter}) db.collectionName.deleteMany({filter})
Advanced Operations
- Sorting Documents
Code
db.collectionName.find().sort({key: 1}) # Sort documents in ascending order - Counting Documents
Code
db.collectionName.find({}).count() # Count the number of documents in a collection - Renaming Collections
Code
db.collectionName.renameCollection("new_coll", true) # Rename a collection - Validating Collections
Code
db.collectionName.validate({full: true}) # Validate a collection, including data and indexes - Retrieving Collection Size Information
Python
db.collectionName.totalSize() # Get the total size of the collection db.collectionName.totalIndexSize() # Get the total index size of the collection db.collectionName.storageSize() # Get the storage size of the collection
Indexing
- Create Index
Code
db.collectionName.createIndex({key: 1}) - List Indexes
Code
db.collectionName.getIndexes() - Drop Index
Code
db.collectionName.dropIndex("indexName")
Aggregation
Aggregation Pipeline
db.collectionName.aggregate([
{ $match: {} },
{ $group: {} }
])Replication and Sharding
- Check Replica Set Status
Code
rs.status() - Initiate Replica Set
Code
rs.initiate() - Enable Sharding
Code
sh.enableSharding("databaseName") - Shard a Collection
Code
sh.shardCollection("databaseName.collectionName", {shardKey: 1})
Miscellaneous Operations
- Backup Database
Code
mongodump --db databaseName --out /backup/directory - Restore Database
Code
mongorestore /backup/directory - Export Collection
Code
mongoexport --collection=collectionName --db=databaseName --out=/export/path/file.json - Import Collection
Code
mongoimport --collection=collectionName --db=databaseName --file=/import/path/file.json
Connect to MongoDB
- Connect via Mongo Shell
Code
mongo --host hostName --port portNumber -u userName -p password --authenticationDatabase admin - Connect via URI
JavaScript
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb://username:password@host:port/database"; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); client.connect(err => { const collection = client.db("database").collection("collectionName"); // perform actions on the collection object client.close(); });
Transactions in MongoDB
In MongoDB, multi-document transactions are supported for replica sets. Transactions allow you to perform multiple operations on multiple documents in a consistent manner. Here's the syntax and an example of how to use transactions in MongoDB.
session.startTransaction();
try {
// Perform multiple operations
db.collection1.insertOne({ field: value });
db.collection2.updateOne({ filter }, { $set: { field: value } });
// If everything is successful, commit the transaction
session.commitTransaction();
} catch (error) {
// If any operation fails, abort the transaction
session.abortTransaction();
print("Transaction aborted:", error);
}Example
Suppose we have two collections: customers and orders. We want to update the status of an order and decrease the available quantity of a product in an atomic operation. Here's how you can do it with a transaction:
session.startTransaction();
try {
// Update order status
db.orders.updateOne(
{ _id: orderId },
{ $set: { status: "shipped" } }
);
// Decrement product quantity
db.products.updateOne(
{ _id: productId },
{ $inc: { quantity: -1 } }
);
// If everything is successful, commit the transaction
session.commitTransaction();
print("Transaction committed successfully!");
} catch (error) {
// If any operation fails, abort the transaction
session.abortTransaction();
print("Transaction aborted:", error);
}In this example, if either the update of the order status or the decrement of the product quantity fails, the entire transaction will be aborted, ensuring data consistency.
Tips
- Use explain(): To understand query performance.
Code
db.collectionName.find({ key: "value" }).explain("executionStats") - Avoid Using eval(): For security reasons, avoid using db. eval().
- Use
bulkWrite(): For performing multiple write operations in a single batch.
Conclusion
This MongoDB cheat sheet provides a quick reference for essential commands and operations commonly used in MongoDB development. By familiarizing yourself with these commands, you can streamline your MongoDB workflow and efficiently manage your databases.


Join the conversation! Your thoughts help the community grow.