# mongosh — The MongoDB Shell

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

Source: https://www.jpkc.com/db/en/cheatsheets/build-languages/mongosh/

<!-- PROSE:intro -->
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.
<!-- PROSE:intro:end -->

## Connect

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

```bash
mongosh
```

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

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

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

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

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

```bash
mongosh -u admin -p secret --authenticationDatabase admin
```

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

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

## Database & Collection

`show dbs` — List all databases.

```bash
show dbs
```

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

```bash
use myapp
```

`show collections` — List all collections in the current database.

```bash
show collections
```

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

```bash
db.createCollection('logs')
```

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

```bash
db.temp_data.drop()
```

`db.dropDatabase()` — Drop the current database.

```bash
db.dropDatabase()
```

## CRUD Operations

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Query & Aggregation

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

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

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

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

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

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

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

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

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

```bash
db.users.distinct('country')
```

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

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

## Indexes

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

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

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

```bash
db.users.getIndexes()
```

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

```bash
db.users.dropIndex('email_1')
```

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

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

## Administration

`db.stats()` — Show database statistics.

```bash
db.stats()
```

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

```bash
db.users.stats()
```

`db.currentOp()` — Show currently running operations.

```bash
db.currentOp()
```

`db.serverStatus()` — Show detailed server status.

```bash
db.serverStatus().connections
```

`rs.status()` — Show replica set status.

```bash
rs.status()
```

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

```bash
db.version()
```

<!-- PROSE:outro -->
## 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](https://www.mongodb.com/docs/mongodb-shell/) – official reference for installation, configuration and commands
- [MongoDB Manual](https://www.mongodb.com/docs/manual/) – complete documentation for queries, aggregation and administration
<!-- PROSE:outro:end -->

## Related Commands

- [artisan](https://www.jpkc.com/db/en/cheatsheets/build-languages/artisan/) – command-line tool of the Laravel framework (PHP)
- [cargo](https://www.jpkc.com/db/en/cheatsheets/build-languages/cargo/) – package manager and build tool for Rust
- [composer](https://www.jpkc.com/db/en/cheatsheets/build-languages/composer/) – dependency manager for PHP projects

