This cheatsheet provides a quick reference for essential MongoDB Shell (mongosh) commands and operations. It covers database and collection management, CRUD operations, indexing, aggregation, and useful utility commands to help you work efficiently with MongoDB.
Connection#
mongosh # Connect to localhost:27017
mongosh "mongodb://host:port" # Connect to remote instance
mongosh --username user --password pass --authenticationDatabase admin
Database Operations#
show dbs // List all databases
use mydb // Switch to database
db // Show current database
db.dropDatabase() // Delete current database
Collection Operations#
show collections // List collections
db.createCollection("mycoll") // Create collection
db.mycoll.drop() // Delete collection
db.mycoll.stats() // Collection statistics
CRUD Operations#
Insert#
db.mycoll.insertOne({name: "John", age: 30})
db.mycoll.insertMany([{name: "Jane"}, {name: "Bob"}])
Find#
db.mycoll.find() // Find all documents
db.mycoll.findOne() // Find first document
db.mycoll.find({name: "John"}) // Find with filter
db.mycoll.find({age: {$gt: 25}}) // Find with condition
db.mycoll.find().limit(5) // Limit results
db.mycoll.find().sort({age: -1}) // Sort descending
Update#
db.mycoll.updateOne({name: "John"}, {$set: {age: 31}})
db.mycoll.updateMany({age: {$lt: 30}}, {$inc: {age: 1}})
db.mycoll.replaceOne({name: "John"}, {name: "John", age: 32})
Delete#
db.mycoll.deleteOne({name: "John"})
db.mycoll.deleteMany({age: {$lt: 18}})
Query Operators#
// Comparison
{age: {$eq: 30}} // Equal
{age: {$ne: 30}} // Not equal
{age: {$gt: 25}} // Greater than
{age: {$gte: 25}} // Greater than or equal
{age: {$lt: 30}} // Less than
{age: {$lte: 30}} // Less than or equal
{age: {$in: [25, 30, 35]}} // In array
// Logical
{$and: [{age: {$gt: 20}}, {age: {$lt: 40}}]}
{$or: [{name: "John"}, {name: "Jane"}]}
{$not: {age: {$gt: 30}}}
Indexes#
db.mycoll.createIndex({name: 1}) // Create ascending index
db.mycoll.createIndex({name: -1}) // Create descending index
db.mycoll.createIndex({name: 1, age: -1}) // Compound index
db.mycoll.getIndexes() // List indexes
db.mycoll.dropIndex({name: 1}) // Drop index
Aggregation#
db.mycoll.aggregate([
{$match: {age: {$gt: 25}}},
{$group: {_id: "$department", avgAge: {$avg: "$age"}}},
{$sort: {avgAge: -1}}
])
Utility Commands#
db.mycoll.count() // Count documents
db.mycoll.distinct("name") // Get distinct values
db.mycoll.explain() // Query execution plan
db.serverStatus() // Server status
exit // Exit mongosh
