MongoDBMongoDB Shell

MongoDB Shell (mongosh)

mongosh is the official MongoDB Shell — a Node.js REPL for interacting with MongoDB. It replaced the legacy mongo shell in MongoDB 5.0+ and supports modern JavaScript, autocompletion, and a configurable prompt.

Connecting to MongoDB

Connection examples

Bash
# Connect to local MongoDB on the default port (27017)
mongosh

# Connect to a specific port
mongosh --port 27018

# Connect with authentication
mongosh --username admin --password secret --authenticationDatabase admin

# Connect to MongoDB Atlas
mongosh "mongodb+srv://cluster0.xxxxx.mongodb.net/myDatabase"   --username myUser
Essential Shell Commands

Command

Description

Example

show dbs

List all databases

show dbs

use <db>

Switch to (or create) a database

use myapp

show collections

List collections in current db

show collections

db.stats()

Show database statistics

db.stats()

db.version()

Show MongoDB server version

db.version()

db.hello()

Show replica set info and connection details

db.hello()

exit / .exit / quit()

Exit the shell

exit

Database Operations

Database operations

JS
// List all databases
show dbs

// Switch to a database (created on first write)
use mydb

// Get the current database name
db.getName()

// Drop the current database
db.dropDatabase()
Collection Operations

Collection operations

JS
// Explicitly create a collection with options
db.createCollection("users", { capped: false })

// List all collection names
db.getCollectionNames()

// Get collection statistics
db.users.stats()

// Drop a collection
db.users.drop()
Running Your First Queries

Basic CRUD in mongosh

JS
// Insert a single document
db.users.insertOne({ name: "Alice", age: 30, city: "Berlin" })

// Insert multiple documents
db.users.insertMany([
  { name: "Bob",   age: 25, city: "Paris" },
  { name: "Carol", age: 35, city: "Tokyo" },
])

// Find all documents
db.users.find()

// Find with a filter
db.users.find({ city: "Berlin" })

// Update a document
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31 } }
)

// Delete a document
db.users.deleteOne({ name: "Bob" })
Using Variables and JavaScript

JavaScript in mongosh

JS
// Assign a document to a variable
var user = { name: "Dave", role: "admin", active: true }
db.users.insertOne(user)

// Insert multiple documents with a loop
for (let i = 1; i <= 5; i++) {
  db.products.insertOne({ sku: `PROD-${i}`, price: i * 10 })
}

// Define and call a helper function
function countActive() {
  return db.users.countDocuments({ active: true })
}
countActive()
mongosh Configuration

mongosh loads ~/.mongoshrc.js at startup. You can use it to set a custom prompt, define helper functions, or connect to a database automatically.

~/.mongoshrc.js

JS
// Show current database in the prompt
prompt = function () {
  return db.getName() + "> "
}

// Shorthand helper
globalThis.lf = (coll) => db[coll].find().toArray()
Running Script Files

Bash
# Run a JavaScript file against the local server
mongosh script.js

# Run a one-liner without opening an interactive session
mongosh --eval "db.users.countDocuments()"

# Run a script against a remote server
mongosh "mongodb+srv://cluster0.xxxxx.mongodb.net/mydb" seed.js
Useful Helpers
  • .pretty() is no longer needed — mongosh formats output automatically

  • cursor.toArray() — converts a cursor to a plain JavaScript array

  • cursor.forEach(fn) — iterates over every document in a cursor

  • db.collection.explain() — returns the query plan instead of results

  • db.collection.explain("executionStats") — includes execution statistics

Tip
Use Tab for autocompletion in mongosh — it knows MongoDB method names and your collection names. Press Tab twice to see all available options.
Note
mongosh supports modern JavaScript (ES2020+) including async/await, optional chaining, and nullish coalescing — the legacy mongo shell did not.