mongosh — The MongoDB Shell

Practical guide to mongosh — the modern, JavaScript-based MongoDB shell for connecting, querying, aggregating and managing collections and documents.

mongosh is the modern, JavaScript-based shell for MongoDB and replaces the legacy mongo shell. You type real JavaScript, so you can assemble queries, aggregations and entire administrative scripts right in the console – with autocompletion, syntax highlighting and far clearer error output than its predecessor. This guide walks you through the commands you reach for daily: from connecting to a server through CRUD and aggregation to indexes and administration.

Connect

mongosh — Connect to local MongoDB (localhost:27017).

mongosh

mongosh '<connection-string>' — Connect using a connection URI.

mongosh 'mongodb://user:pass@host:27017/mydb'

mongosh --host <host> --port <port> — Connect to a specific host and port.

mongosh --host db.example.com --port 27017

mongosh -u <user> -p <password> --authenticationDatabase <db> — Connect with authentication.

mongosh -u admin -p secret --authenticationDatabase admin

mongosh --eval '<code>' — Execute JavaScript and exit.

mongosh --eval 'db.users.countDocuments()'

Database & Collection

show dbs — List all databases.

show dbs

use <database> — Switch to a database (creates on first write).

use myapp

show collections — List all collections in the current database.

show collections

db.createCollection('<name>') — Create a new collection explicitly.

db.createCollection('logs')

db.<collection>.drop() — Drop a collection.

db.temp_data.drop()

db.dropDatabase() — Drop the current database.

db.dropDatabase()

CRUD Operations

db.<col>.insertOne({<doc>}) — Insert a single document.

db.users.insertOne({name: 'John', email: 'john@example.com'})

db.<col>.insertMany([{<doc>}, {<doc>}]) — Insert multiple documents.

db.users.insertMany([{name: 'John'}, {name: 'Jane'}])

db.<col>.find({<filter>}) — Find documents matching a filter.

db.users.find({age: {$gte: 18}})

db.<col>.findOne({<filter>}) — Find the first matching document.

db.users.findOne({email: 'john@example.com'})

db.<col>.updateOne({<filter>}, {$set: {<fields>}}) — Update a single document.

db.users.updateOne({name: 'John'}, {$set: {age: 30}})

db.<col>.updateMany({<filter>}, {$set: {<fields>}}) — Update multiple documents.

db.users.updateMany({active: false}, {$set: {archived: true}})

db.<col>.deleteOne({<filter>}) — Delete a single document.

db.users.deleteOne({name: 'John'})

db.<col>.deleteMany({<filter>}) — Delete multiple documents.

db.users.deleteMany({archived: true})

Query & Aggregation

db.<col>.find().sort({<field>: 1}) — Sort results (1=ascending, -1=descending).

db.users.find().sort({name: 1})

db.<col>.find().limit(<n>) — Limit the number of results.

db.users.find().limit(10)

db.<col>.find({}, {<field>: 1}) — Projection: return only specific fields.

db.users.find({}, {name: 1, email: 1, _id: 0})

db.<col>.countDocuments({<filter>}) — Count documents matching a filter.

db.users.countDocuments({active: true})

db.<col>.distinct('<field>') — Get distinct values for a field.

db.users.distinct('country')

db.<col>.aggregate([{$group: {_id: '$<field>', count: {$sum: 1}}}]) — Group and aggregate documents.

db.orders.aggregate([{$group: {_id: '$status', count: {$sum: 1}}}])

Indexes

db.<col>.createIndex({<field>: 1}) — Create an ascending index on a field.

db.users.createIndex({email: 1}, {unique: true})

db.<col>.getIndexes() — List all indexes on a collection.

db.users.getIndexes()

db.<col>.dropIndex('<name>') — Drop an index by name.

db.users.dropIndex('email_1')

db.<col>.find({<filter>}).explain('executionStats') — Explain query execution plan.

db.users.find({email: 'john@example.com'}).explain('executionStats')

Administration

db.stats() — Show database statistics.

db.stats()

db.<col>.stats() — Show collection statistics.

db.users.stats()

db.currentOp() — Show currently running operations.

db.currentOp()

db.serverStatus() — Show detailed server status.

db.serverStatus().connections

rs.status() — Show replica set status.

rs.status()

db.version() — Show the MongoDB server version.

db.version()

Conclusion

mongosh makes day-to-day work with MongoDB pleasant: because the shell understands real JavaScript, one-off queries are as easy as small scripts you launch straight from the terminal with --eval. A few commands are irreversible, though – db.dropDatabase(), db.<col>.drop() and a deleteMany({}) without a filter delete with no confirmation and no recycle bin, so check where you are with use and countDocuments first. Connection strings with plaintext passwords otherwise end up in your shell history or a Git repo – use environment variables or the interactive password prompt instead. And --eval runs whatever you hand it, so reach for it carefully with delete and update commands.

Further Reading

  • mongosh documentation – official reference for installation, configuration and commands
  • MongoDB Manual – complete documentation for queries, aggregation and administration
  • artisan – command-line tool of the Laravel framework (PHP)
  • cargo – package manager and build tool for Rust
  • composer – dependency manager for PHP projects