
Here are some essential (mongosh) (MongoDB Shell) commands, categorized for easy understanding.
MongoDB Shell (mongosh) Commands
1. Connecting to MongoDB
mongosh # Connect to MongoDB locally
mongosh "mongodb://localhost:27017" # Connect to a specific host and port
mongosh "mongodb+srv://username:password@cluster.mongodb.net/dbname" # Connect to a remote database
2. Database Operations
show dbs # List all databases
use myDatabase # Switch to (or create) a database
db # Show the current database
db.dropDatabase() # Delete the current database
3. Collection Operations
show collections # List all collections in the database
db.createCollection("users") # Create a new collection
db.users.drop() # Delete a collection
4. Insert Documents
db.users.insertOne({ name: "John", age: 25 }) # Insert a single document
db.users.insertMany([{ name: "Alice", age: 22 }, { name: "Bob", age: 30 }]) # Insert multiple documents
5. Query Documents
db.users.find() # Retrieve all documents
db.users.find().pretty() # Format the output nicely
db.users.find({ name: "John" }) # Find documents with a specific name
db.users.findOne({ age: 25 }) # Retrieve one matching document
db.users.find({ age: { $gt: 20 } }) # Find users with age greater than 20
6. Update Documents
db.users.updateOne({ name: "John" }, { $set: { age: 26 } }) # Update one document
db.users.updateMany({ age: { $lt: 30 } }, { $set: { status: "young" } }) # Update multiple documents
db.users.replaceOne({ name: "John" }, { name: "John Doe", age: 26 }) # Replace a document completely
7. Delete Documents
db.users.deleteOne({ name: "John" }) # Delete one document
db.users.deleteMany({ age: { $lt: 18 } }) # Delete multiple documents
8. Indexing
db.users.createIndex({ name: 1 }) # Create an ascending index on "name"
db.users.getIndexes() # Show all indexes
db.users.dropIndex("name_1") # Drop an index
9. Aggregation
db.users.aggregate([
{ $match: { age: { $gt: 20 } } },
{ $group: { _id: "$status", count: { $sum: 1 } } }
])
10. User & Role Management
db.createUser({
user: "admin",
pwd: "password123",
roles: [{ role: "readWrite", db: "myDatabase" }]
})
db.getUsers() # List all users
db.dropUser("admin") # Delete a user
11. Backup & Restore
mongodump --db=myDatabase --out=/backup # Backup database
mongorestore --db=myDatabase /backup/myDatabase # Restore database
12. Exiting the Shell
exit # Exit mongosh
This covers most of the essential mongosh commands. Let me know if you need anything specific! 🚀