Database
mongosh CLI
MongoDB Shell commands for document database management.
38 commands
Windows
MacOS
Linux
#mongodb
#nosql
Connection
Connect to local MongoDB on default port
mongosh
Connect to a specific database via URI
mongosh "mongodb://localhost:27017/mydb"
Connect to a remote MongoDB host
mongosh --host 192.168.1.10 --port 27017
Connect with authentication
mongosh --username admin --authenticationDatabase admin
Connect to MongoDB Atlas cluster
mongosh "mongodb+srv://user:[email protected]/db"
CRUD Operations
Insert a single document
db.users.insertOne({name: "Alice", age: 30})
Insert multiple documents
db.users.insertMany([{name: "Bob"}, {name: "Carol"}])
Find documents matching a query
db.users.find({age: {$gt: 25}})
Find one document by condition
db.users.findOne({name: "Alice"})
Update a single document
db.users.updateOne({name: "Alice"}, {$set: {age: 31}})
Delete a single document
db.users.deleteOne({name: "Bob"})
Delete all matching documents
db.users.deleteMany({age: {$lt: 18}})
Count all documents in a collection
db.users.countDocuments({})
Aggregation
Group and count by field
db.orders.aggregate([{$group: {_id: "$status", count: {$sum: 1}}}])
Filter documents in pipeline
db.orders.aggregate([{$match: {total: {$gt: 100}}}])
Sort descending and limit
db.orders.aggregate([{$sort: {total: -1}}, {$limit: 10}])
Flatten an array field
db.orders.aggregate([{$unwind: "$items"}])
Select specific fields
db.orders.aggregate([{$project: {name: 1, total: 1, _id: 0}}])
Indexes
Create an ascending index on a field
db.users.createIndex({email: 1})
Create a unique index
db.users.createIndex({email: 1}, {unique: true})
List all indexes on a collection
db.users.getIndexes()
Drop a specific index
db.users.dropIndex({email: 1})
Create a text search index
db.users.createIndex({name: "text"})
Database Admin
List all databases with sizes
show dbs
Switch to a database
use mydb
Show database statistics
db.stats()
Drop the current database
db.dropDatabase()
Show server status information
db.serverStatus()
Show currently running operations
db.currentOp()
Collections
List all collections in current database
show collections
Create a new collection
db.createCollection("logs")
Drop a collection
db.logs.drop()
Rename a collection
db.logs.renameCollection("audit_logs")
Get distinct values of a field
db.users.distinct("city")
Fast approximate document count
db.users.estimatedDocumentCount()
Quick Commands
Connect to a local MongoDB database
mongosh "mongodb://localhost:27017/mydb"
Query documents where age is greater than 25
db.users.find({age: {$gt: 25}})
Create a unique index on the email field
db.users.createIndex({email: 1}, {unique: true})