The Ultimate List of MongoDB Commands Categorized by Usage
MongoDB is a powerful NoSQL database known for its flexibility and scalability. Whether you are a beginner or an advanced user, mastering MongoDB commands will help you efficiently manage databases, collections, and documents. This guide categorizes MongoDB commands based on their usage, covering everything from basic operations to advanced database management.
1. Basic MongoDB Commands
Starting and Stopping MongoDB
- Start MongoDB:
sudo systemctl start mongod
- Stop MongoDB:
sudo systemctl stop mongod
- Restart MongoDB:
sudo systemctl restart mongod
- Check MongoDB status:
sudo systemctl status mongod
Connecting to MongoDB
- Open MongoDB shell:
mongo
- Connect to a specific database:
use <database_name>
- Show available databases:
show dbs
- Show the currently selected database:
db
2. Database Management
Creating a Database
MongoDB automatically creates a database when a document is inserted. However, you can explicitly select a database:
use myDatabase
(This does not create the database until data is added.)
Dropping a Database
db.dropDatabase()
Deletes the currently selected database.
Listing All Databases
show dbs
Displays all available databases.
Checking the Current Database
db
Displays the name of the currently selected database.
3. Collection Management
Creating a Collection
db.createCollection("myCollection")
Creates an empty collection.
Listing All Collections
show collections
Displays all collections in the current database.
Dropping a Collection
db.myCollection.drop()
Deletes a specific collection.
4. Document Management (CRUD Operations)
Inserting Documents
- Insert a single document:
db.myCollection.insertOne({ name: "Alice", age: 25, city: "New York" })
- Insert multiple documents:
db.myCollection.insertMany([
{ name: "Bob", age: 30, city: "Los Angeles" },
{ name: "Charlie", age: 35, city: "Chicago" }
])
Reading Documents (Querying)
- Find all documents in a collection:
db.myCollection.find()
- Find a specific document:
db.myCollection.findOne({ name: "Alice" })
- Find documents with specific conditions:
db.myCollection.find({ age: { $gt: 30 } })
Finds all documents where age
is greater than 30.
- Projection (return only specific fields):
db.myCollection.find({ }, { name: 1, _id: 0 })
Returns only the name
field and excludes _id
.
Updating Documents
- Update a single document:
db.myCollection.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)
- Update multiple documents:
db.myCollection.updateMany(
{ city: "New York" },
{ $set: { country: "USA" } }
)
- Replace a document:
db.myCollection.replaceOne(
{ name: "Alice" },
{ name: "Alice", age: 27, city: "Boston" }
)
Deleting Documents
- Delete a single document:
db.myCollection.deleteOne({ name: "Alice" })
- Delete multiple documents:
db.myCollection.deleteMany({ city: "Los Angeles" })
5. Indexing and Performance Optimization
Creating Indexes
- Create an index on a field:
db.myCollection.createIndex({ name: 1 })
- Create a compound index:
db.myCollection.createIndex({ name: 1, age: -1 })
- Create a unique index:
db.myCollection.createIndex({ email: 1 }, { unique: true })
Listing Indexes
db.myCollection.getIndexes()
Dropping an Index
db.myCollection.dropIndex("name_1")
6. Aggregation Framework
Using Aggregation Pipelines
- Count documents in a collection:
db.myCollection.countDocuments()
- Group and count by a field:
db.myCollection.aggregate([
{ $group: { _id: "$city", count: { $sum: 1 } } }
])
- Sort documents:
db.myCollection.aggregate([
{ $sort: { age: -1 } }
])
7. User and Role Management
Creating a User
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [ { role: "readWrite", db: "myDatabase" } ]
})
Listing Users
db.getUsers()
Deleting a User
db.dropUser("adminUser")
8. Backup and Restore
Backup a Database
mongodump --db myDatabase --out /backup/
Restore a Database
mongorestore --db myDatabase /backup/myDatabase/
9. Replica Sets and Sharding
Checking Replica Set Status
rs.status()
Initiating a Replica Set
rs.initiate()
Adding a Member to a Replica Set
rs.add("mongodb2.example.com:27017")
Sharding a Collection
sh.enableSharding("myDatabase")
10. Server Administration and Monitoring
Checking MongoDB Server Status
db.serverStatus()
Checking Database Stats
db.stats()
Checking Collection Stats
db.myCollection.stats()
Logging Slow Queries
db.setProfilingLevel(1)
Enabling Authorization
Edit /etc/mongod.conf
and add:
security:
authorization: enabled
Restart MongoDB:
sudo systemctl restart mongod
Conclusion
This guide provides a categorized reference for essential MongoDB commands. Whether you are working with collections, queries, indexes, or replication, these commands will help you efficiently manage MongoDB databases. Keep this guide handy as a quick reference! 🚀
Top comments (0)