MongoDB Cheat Sheet

MongoDB is a NoSQL database that uses a document-oriented model to store data. Below is a concise MongoDB cheat sheet covering some common commands and operations:

Basic Operations

Connect to MongoDB:

mongo

Show Databases:

show dbs

Switch Database:

use <database_name>

Show Collections in Current Database:

show collections

CRUD Operations

Insert Document:

db.collection_name.insert({ key: "value" })

Find Documents:

db.collection_name.find()

Update Document:

db.collection_name.update({ key: "value" }, { $set: { key2: "new_value" } })

Delete Document:

db.collection_name.remove({ key: "value" })

Query Operators

Equality:

db.collection_name.find({ key: "value" })

Greater Than:

db.collection_name.find({ key: { $gt: 5 } })

Less Than:

db.collection_name.find({ key: { $lt: 10 } })

Logical AND:

db.collection_name.find({ $and: [{ key1: "value1" }, { key2: "value2" }] })

Indexing

Create Index:

db.collection_name.createIndex({ key: 1 })

List Indexes:

db.collection_name.getIndexes()

Aggregation

Basic Aggregation:

db.collection_name.aggregate([
  { $match: { key: "value" } },
  { $group: { _id: "$key", count: { $sum: 1 } } }
])

Backup and Restore

Backup Database:

mongodump --db <database_name> --out <backup_directory>

Restore Database:

mongorestore --db <database_name> <backup_directory>/<database_name>

Miscellaneous

Show Server Status:

db.serverStatus()

Show Current Database:

db

This cheat sheet provides a quick reference for common MongoDB commands and operations. MongoDB has a rich set of features, and you may need to refer to the official MongoDB documentation for more in-depth information on specific topics.