1. Database Operations
- Show Databases
List all databases. bashCopyEditshow dbs
- Use Database
Switch to a specific database. If the database does not exist, it will be created when data is inserted. bashCopyEdituse <database_name>
- Create Database
MongoDB automatically creates a database when you insert data, but you can explicitly create one by switching to a database and adding data. bashCopyEdituse <database_name> db.createCollection("<collection_name>")
- Drop Database
Delete a database. bashCopyEditdb.dropDatabase()
2. Collection Operations
- Show Collections
List all collections in the current database. bashCopyEditshow collections
- Create Collection
Create a collection (optional, as MongoDB creates collections automatically). bashCopyEditdb.createCollection("<collection_name>")
- Drop Collection
Delete a collection. bashCopyEditdb.<collection_name>.drop()
3. CRUD Operations (Insert, Read, Update, Delete)
- Insert Document
Insert a single document into a collection. bashCopyEditdb.<collection_name>.insertOne({ field1: "value1", field2: "value2" })
- Insert Multiple Documents
Insert multiple documents at once. bashCopyEditdb.<collection_name>.insertMany([{ field1: "value1" }, { field2: "value2" }])
- Find Documents
Retrieve all documents from a collection. bashCopyEditdb.<collection_name>.find()
- Find with Query
Retrieve documents that match a specific query. bashCopyEditdb.<collection_name>.find({ field: "value" })
- Update Document
Update a single document that matches the query. bashCopyEditdb.<collection_name>.updateOne( { <query> }, { $set: { <field>: <new_value> } } )
- Update Multiple Documents
Update multiple documents that match the query. bashCopyEditdb.<collection_name>.updateMany( { <query> }, { $set: { <field>: <new_value> } } )
- Delete Document
Delete a single document that matches the query. bashCopyEditdb.<collection_name>.deleteOne({ <query> })
- Delete Multiple Documents
Delete multiple documents that match the query. bashCopyEditdb.<collection_name>.deleteMany({ <query> })
4. Query Operators
- Equality
Matches documents where the field equals a specified value. bashCopyEditdb.<collection_name>.find({ field: "value" })
- Greater Than
Matches documents where the field is greater than the specified value. bashCopyEditdb.<collection_name>.find({ field: { $gt: value } })
- Less Than
Matches documents where the field is less than the specified value. bashCopyEditdb.<collection_name>.find({ field: { $lt: value } })
- Greater Than or Equal To
Matches documents where the field is greater than or equal to the specified value. bashCopyEditdb.<collection_name>.find({ field: { $gte: value } })
- Less Than or Equal To
Matches documents where the field is less than or equal to the specified value. bashCopyEditdb.<collection_name>.find({ field: { $lte: value } })
- Not Equal
Matches documents where the field is not equal to the specified value. bashCopyEditdb.<collection_name>.find({ field: { $ne: value } })
- In
Matches documents where the field’s value is in a specified list. bashCopyEditdb.<collection_name>.find({ field: { $in: [value1, value2] } })
- Not In
Matches documents where the field’s value is not in a specified list. bashCopyEditdb.<collection_name>.find({ field: { $nin: [value1, value2] } })
- Exists
Matches documents where the field exists. bashCopyEditdb.<collection_name>.find({ field: { $exists: true } })
5. Projection
- Select Specific Fields
Retrieve specific fields from documents. bashCopyEditdb.<collection_name>.find({}, { field1: 1, field2: 1 })
- Exclude Fields
Exclude specific fields from the results. bashCopyEditdb.<collection_name>.find({}, { field1: 0 })
6. Sorting and Limiting Results
- Sort Documents
Sort documents by a field in ascending or descending order. bashCopyEditdb.<collection_name>.find().sort({ field: 1 }) # Ascending db.<collection_name>.find().sort({ field: -1 }) # Descending
- Limit Results
Limit the number of documents returned. bashCopyEditdb.<collection_name>.find().limit(10)
7. Indexing
- Create Index
Create an index on a field to improve query performance. bashCopyEditdb.<collection_name>.createIndex({ field: 1 }) # Ascending index
- List Indexes
List all indexes on a collection. bashCopyEditdb.<collection_name>.getIndexes()
- Drop Index
Drop an index from a collection. bashCopyEditdb.<collection_name>.dropIndex("<index_name>")
8. Aggregation
- Aggregation Pipeline
MongoDB provides a powerful aggregation framework to perform complex queries and transformations on data. - Simple Aggregation Example
Group documents by a specific field and calculate the sum of a numeric field. bashCopyEditdb.<collection_name>.aggregate([ { $group: { _id: "$field", total: { $sum: "$numericField" } } } ])
- Match Documents
Apply a filter at the beginning of the aggregation pipeline. bashCopyEditdb.<collection_name>.aggregate([ { $match: { field: "value" } } ])
9. Backup and Restore
- Backup Database
Create a backup of your database. bashCopyEditmongodump --db <database_name> --out <backup_directory>
- Restore Database
Restore a database from a backup. bashCopyEditmongorestore --db <database_name> <backup_directory>
10. Administrative Commands
- Show Server Status
Display detailed information about the current state of the MongoDB server. bashCopyEditdb.serverStatus()
- Check Database Stats
View statistics about the current database. bashCopyEditdb.stats()
- Check Collection Stats
View statistics about a collection. bashCopyEditdb.<collection_name>.stats()
Conclusion
This cheat sheet covers the essential MongoDB commands that you will use regularly for managing databases, performing CRUD operations, querying data, and managing indexes. As you grow more familiar with MongoDB, you can explore advanced features like aggregation, replication, sharding, and more.