MongoDB

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/OptionExampleDescription
mongomongoStart the MongoDB shell
mongo <database>mongo mydbConnect to a specific database
use <database>use mydbSwitch to a specific database
dbdbShow the current database
show dbsshow dbsList all databases
show collectionsshow collectionsList all collections in the current database

CRUD Operations #

Command/OptionExampleDescription
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/OptionExampleDescription
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/OptionExampleDescription
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/OptionExampleDescription
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/OptionExampleDescription
mongodumpmongodump --db=mydb --out=/backup/Backup a database
mongorestoremongorestore /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.

MongoDB

Explore our comprehensive cheatsheets to enhance your knowledge and efficiency. Each cheatsheet provides detailed command options, examples, and descriptions to help you master various tools and technologies.