MongoDB Cheatsheet
#
MongoDB is a NoSQL database that provides high performance, high availability, and easy scalability. It stores data in flexible, JSON-like documents.
General Commands
#
Command/Option | Example | Description |
---|
mongo | mongo | Start the MongoDB shell |
mongo <database> | mongo mydb | Connect to a specific database |
use <database> | use mydb | Switch to a specific database |
db | db | Show the current database |
show dbs | show dbs | List all databases |
show collections | show collections | List all collections in the current database |
CRUD Operations
#
Command/Option | Example | Description |
---|
db.collection.insertOne() | db.users.insertOne({ name: "John", age: 30 }) | Insert a single document into a collection |
db.collection.insertMany() | db.users.insertMany([{ name: "Jane" }, { name: "Doe" }]) | Insert multiple documents into a collection |
db.collection.find() | db.users.find({ name: "John" }) | Find documents in a collection |
db.collection.updateOne() | db.users.updateOne({ name: "John" }, { $set: { age: 31 } }) | Update a single document in a collection |
db.collection.updateMany() | db.users.updateMany({}, { $set: { status: "active" } }) | Update multiple documents in a collection |
db.collection.deleteOne() | db.users.deleteOne({ name: "John" }) | Delete a single document from a collection |
db.collection.deleteMany() | db.users.deleteMany({ age: { $lt: 18 } }) | Delete multiple documents from a collection |
Indexes
#
Command/Option | Example | Description |
---|
db.collection.createIndex() | db.users.createIndex({ name: 1 }) | Create an index on a collection |
db.collection.dropIndex() | db.users.dropIndex("name_1") | Drop an index from a collection |
db.collection.getIndexes() | db.users.getIndexes() | List all indexes on a collection |
Aggregation
#
Command/Option | Example | Description |
---|
db.collection.aggregate() | db.orders.aggregate([ { $match: { status: "pending" } }, { $group: { _id: "$customer", total: { $sum: "$amount" } } } ]) | Perform aggregation operations on a collection |
db.collection.countDocuments() | db.orders.countDocuments({ status: "shipped" }) | Count documents that match a query |
Administration
#
Command/Option | Example | Description |
---|
db.stats() | db.stats() | Get statistics about the current database |
db.collection.stats() | db.users.stats() | Get statistics about a specific collection |
db.repairDatabase() | db.repairDatabase() | Repair the current database |
db.dropDatabase() | db.dropDatabase() | Drop the current database |
Backup and Restore
#
Command/Option | Example | Description |
---|
mongodump | mongodump --db=mydb --out=/backup/ | Backup a database |
mongorestore | mongorestore /backup/ | Restore a database from a backup |
This cheatsheet covers the essential MongoDB commands and options, assisting you in performing database operations, managing indexes, and handling backups effectively.