  
---

\# \*\*MongoDB Essential Commands: A Comprehensive Guide\*\*

MongoDB is a leading NoSQL database that stores data in flexible, JSON-like documents. This guide summarizes the most important MongoDB commands for database administration and development.

---

\#\# \*\*1\. Starting the MongoDB Shell\*\*

* \*\*Connect to MongoDB instance:\*\*

\`\`\`shell  
mongo  
\`\`\`

Connects to the default MongoDB instance on \`localhost:27017\`.

* \*\*Connect to a specific database:\*\*

\`\`\`shell  
mongo your\_database\_name  
\`\`\`

---

\#\# \*\*2\. Database Commands\*\*

* \*\*Show all databases:\*\*

\`\`\`javascript  
show dbs  
\`\`\`

* \*\*Switch to or create a database:\*\*

\`\`\`javascript  
use database\_name  
\`\`\`

* \*\*Display current database:\*\*

\`\`\`javascript  
db  
\`\`\`

* \*\*Drop the current database:\*\*

\`\`\`javascript  
db.dropDatabase()  
\`\`\`

---

\#\# \*\*3\. Collection Commands\*\*

* \*\*Show collections in the current database:\*\*

\`\`\`javascript  
show collections  
\`\`\`

* \*\*Create a collection:\*\*

\`\`\`javascript  
db.createCollection('collection\_name')  
\`\`\`

* \*\*Drop a collection:\*\*

\`\`\`javascript  
db.collection\_name.drop()  
\`\`\`

---

\#\# \*\*4\. CRUD Operations\*\*

\#\#\# \*\*Insert Documents\*\*

* \*\*Insert a single document:\*\*

\`\`\`javascript  
db.collection\_name.insertOne({ key: value, ... })  
\`\`\`

* \*\*Insert multiple documents:\*\*

\`\`\`javascript  
db.collection\_name.insertMany(\[{ doc1 }, { doc2 }, ...\])  
\`\`\`

\#\#\# \*\*Find Documents\*\*

* \*\*Find all documents:\*\*

\`\`\`javascript  
db.collection\_name.find()  
\`\`\`

* \*\*Find documents with a filter:\*\*

\`\`\`javascript  
db.collection\_name.find({ key: value })  
\`\`\`

* \*\*Find one document:\*\*

\`\`\`javascript  
db.collection\_name.findOne({ key: value })  
\`\`\`

\#\#\# \*\*Update Documents\*\*

* \*\*Update a single document:\*\*

\`\`\`javascript  
db.collection\_name.updateOne(  
{ filter\_condition },  
{ $set: { key: new\_value } }  
)  
\`\`\`

* \*\*Update multiple documents:\*\*

\`\`\`javascript  
db.collection\_name.updateMany(  
{ filter\_condition },  
{ $set: { key: new\_value } }  
)  
\`\`\`

* \*\*Replace a document:\*\*

\`\`\`javascript  
db.collection\_name.replaceOne(  
{ filter\_condition },  
{ new\_document }  
)  
\`\`\`

\#\#\# \*\*Delete Documents\*\*

* \*\*Delete a single document:\*\*

\`\`\`javascript  
db.collection\_name.deleteOne({ filter\_condition })  
\`\`\`

* \*\*Delete multiple documents:\*\*

\`\`\`javascript  
db.collection\_name.deleteMany({ filter\_condition })  
\`\`\`

---

\#\# \*\*5\. Query Operators\*\*

\#\#\# \*\*Comparison Operators\*\*

* \`$eq\` - Equal to 
* \`$ne\` - Not equal to 
* \`$gt\` - Greater than 
* \`$gte\` - Greater than or equal to 
* \`$lt\` - Less than 
* \`$lte\` - Less than or equal to

\*\*Example:\*\*

\`\`\`javascript  
db.collection\_name.find({ age: { $gt: 25 } })  
\`\`\`

\#\#\# \*\*Logical Operators\*\*

* \`$and\` - Logical AND 
* \`$or\` - Logical OR 
* \`$not\` - Logical NOT 
* \`$nor\` - Logical NOR

\*\*Example:\*\*

\`\`\`javascript  
db.collection\_name.find({  
$and: \[{ status: 'A' }, { score: { $gt: 50 } }\]  
})  
\`\`\`

\#\#\# \*\*Element Operators\*\*

* \`$exists\` - Matches documents that have the specified field 
* \`$type\` - Selects documents if a field is of the specified type

\#\#\# \*\*Array Operators\*\*

* \`$in\` - Matches any of the values specified in an array 
* \`$nin\` - Matches none of the values specified in an array 
* \`$all\` - Matches arrays that contain all elements specified 
* \`$size\` - Selects documents if the array field is a specified size

---

\#\# \*\*6\. Projection\*\*

* \*\*Include or exclude fields in the result set:\*\*

\`\`\`javascript  
db.collection\_name.find(  
{ query\_filter },  
{ field1: 1, field2: 0 }  
)  
\`\`\`

* \`1\` includes the field; \`0\` excludes the field.

---

\#\# \*\*7\. Aggregation Framework\*\*

* \*\*Basic aggregation pipeline:\*\*

\`\`\`javascript  
db.collection\_name.aggregate(\[  
{ $match: { status: 'A' } },  
{ $group: { \_id: '$cust\_id', total: { $sum: '$amount' } } },  
{ $sort: { total: -1 } }  
\])  
\`\`\`

* \*\*Common aggregation stages:\*\*  
* \`$match\` - Filters documents   
* \`$group\` - Groups documents   
* \`$sort\` - Sorts documents   
* \`$project\` - Reshapes documents   
* \`$limit\` - Limits the number of documents   
* \`$skip\` - Skips over documents  

---

\#\# \*\*8\. Indexing\*\*

* \*\*Create an index:\*\*

\`\`\`javascript  
db.collection\_name.createIndex({ field: 1 })  
\`\`\`

* \`1\` for ascending order, \`-1\` for descending order  
* \*\*View existing indexes:\*\*  

\`\`\`javascript  
db.collection\_name.getIndexes()  
\`\`\`

* \*\*Drop an index:\*\*

\`\`\`javascript  
db.collection\_name.dropIndex('index\_name')  
\`\`\`

---

\#\# \*\*9\. Bulk Operations\*\*

* \*\*Initialize bulk operation:\*\*

\`\`\`javascript  
var bulk = db.collection\_name.initializeOrderedBulkOp()  
\`\`\`

* \*\*Add operations:\*\*

\`\`\`javascript  
bulk.insert({ document })  
bulk.find({ query }).update({ $set: { key: value } })  
bulk.find({ query }).remove()  
\`\`\`

* \*\*Execute bulk operation:\*\*

\`\`\`javascript  
bulk.execute()  
\`\`\`

---

\#\# \*\*10\. Administrative Commands\*\*

* \*\*Check server status:\*\*

\`\`\`javascript  
db.serverStatus()  
\`\`\`

* \*\*Get database statistics:\*\*

\`\`\`javascript  
db.stats()  
\`\`\`

* \*\*Get collection statistics:\*\*

\`\`\`javascript  
db.collection\_name.stats()  
\`\`\`

---

\#\# \*\*11\. User Management\*\*

* \*\*Create a user:\*\*

\`\`\`javascript  
db.createUser({  
user: 'username',  
pwd: 'password',  
roles: \[{ role: 'roleName', db: 'databaseName' }\]  
})  
\`\`\`

* \*\*Authenticate a user:\*\*

\`\`\`javascript  
db.auth('username', 'password')  
\`\`\`

* \*\*Show users:\*\*

\`\`\`javascript  
show users  
\`\`\`

* \*\*Drop a user:\*\*

\`\`\`javascript  
db.dropUser('username')  
\`\`\`

---

\#\# \*\*12\. Backup and Restore\*\*

* \*\*Backup a database:\*\*

\`\`\`shell  
mongodump --db database\_name --out /backup/directory  
\`\`\`

* \*\*Restore a database:\*\*

\`\`\`shell  
mongorestore /backup/directory/database\_name  
\`\`\`

---

\#\# \*\*13\. Miscellaneous Commands\*\*

* \*\*Limit the number of documents returned:\*\*

\`\`\`javascript  
db.collection\_name.find().limit(5)  
\`\`\`

* \*\*Skip a number of documents:\*\*

\`\`\`javascript  
db.collection\_name.find().skip(10)  
\`\`\`

* \*\*Sort documents:\*\*

\`\`\`javascript  
db.collection\_name.find().sort({ field: 1 })  
\`\`\`

* \*\*Count documents:\*\*

\`\`\`javascript  
db.collection\_name.countDocuments({ query\_filter })  
\`\`\`

---

\#\# \*\*14\. Transactions (Replica Sets and Sharded Clusters)\*\*

* \*\*Start a session and transaction:\*\*

\`\`\`javascript  
const session = db.getMongo().startSession()  
session.startTransaction()  
\`\`\`

* \*\*Perform operations within the transaction:\*\*

\`\`\`javascript  
session.getDatabase('db\_name').collection\_name.insertOne({ ... })  
\`\`\`

* \*\*Commit the transaction:\*\*

\`\`\`javascript  
session.commitTransaction()  
session.endSession()  
\`\`\`

* \*\*Abort the transaction:\*\*

\`\`\`javascript  
session.abortTransaction()  
session.endSession()  
\`\`\`

---

\#\# \*\*15\. MongoDB Shell Helpers\*\*

* \*\*Iterate over query results:\*\*

\`\`\`javascript  
var cursor = db.collection\_name.find()  
while (cursor.hasNext()) {  
printjson(cursor.next())  
}  
\`\`\`

* \*\*Pretty print query results:\*\*

\`\`\`javascript  
db.collection\_name.find().pretty()  
\`\`\` 