$ command-helper

MongoDB

mongosh, queries and updates, indexes, aggregation, mongodump backups and diagnostics.

Requires Google sign-in

Connecting

Connect with a connection string
mongosh "mongodb://<user>@<host>:27017/<database>?authSource=admin"
List databases
show dbs
Switch database
use <database>
List collections
show collections

Queries

Find documents by a field
db.<collection>.find({ status: "active" }).limit(10)
Find one by _id
db.<collection>.findOne({ _id: ObjectId("<id>") })
Comparison and projection
db.<collection>.find({ age: { $gte: 18 } }, { name: 1, email: 1 })
Sort, skip and limit
db.<collection>.find().sort({ createdAt: -1 }).skip(20).limit(10)
Count documents
db.<collection>.countDocuments({ status: "active" })
Distinct values of a field
db.<collection>.distinct("status")

Changing data

Insert a document
db.<collection>.insertOne({ name: "Alice", createdAt: new Date() })
Update a field
db.<collection>.updateOne({ _id: ObjectId("<id>") }, { $set: { status: "done" } })
Update many documents
db.<collection>.updateMany({ status: "new" }, { $set: { status: "pending" } })
Delete documents
db.<collection>.deleteMany({ status: "archived" })

Indexes and aggregation

Create an index
db.<collection>.createIndex({ email: 1 }, { unique: true })
List indexes
db.<collection>.getIndexes()
Explain a queryadvanced
db.<collection>.find({ email: "a@b.c" }).explain("executionStats")
Group and countadvanced
db.<collection>.aggregate([
  { $match: { status: "active" } },
  { $group: { _id: "$country", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

Backups and diagnostics

Dump a database
mongodump --uri "mongodb://<user>@<host>:27017/<database>?authSource=admin" --gzip --archive=<database>.gz
Restore a dump
mongorestore --uri "mongodb://<user>@<host>:27017" --gzip --archive=<database>.gz
Collection size and statsadvanced
db.<collection>.stats({ scale: 1024 * 1024 })
Running operations longer than 5 secondsadvanced
db.currentOp({ active: true, secs_running: { $gt: 5 } })
Kill an operationadvanced
db.killOp(<opid>)
Replica set statusadvanced
rs.status()