MongoDB Shell

mongosh cheatsheet — query, insert, update, delete MongoDB documents. db.collection.find(), insertOne, updateMany, aggregate pipeline. Full MongoDB shell reference.

7 min read

What it is

The mongosh is the modern, interactive JavaScript shell for MongoDB, used for querying, updating, and managing your MongoDB databases.

Installation

Linux

# Using apt (Debian/Ubuntu)
sudo apt update
sudo apt install mongosh

# Using dnf (Fedora/CentOS/RHEL)
sudo dnf install mongosh

# Using yum (Older CentOS/RHEL)
sudo yum install epel-release
sudo yum install mongosh

# From official binaries
wget https://downloads.mongodb.org/tools/db/mongosh/mongodb-mongosh-linux64-x86_64-1.10.1.tgz
tar -xzf mongodb-mongosh-linux64-x86_64-1.10.1.tgz
export PATH=$PATH:/path/to/mongodb-mongosh-linux64-x86_64-1.10.1/bin

macOS

# Using Homebrew
brew install mongosh

# From official binaries
curl -LO https://downloads.mongodb.org/tools/db/mongosh/mongodb-mongosh-macos-x86_64-1.10.1.tgz
tar -xzf mongodb-mongosh-macos-x86_64-1.10.1.tgz
export PATH=$PATH:/path/to/mongodb-mongosh-macos-x86_64-1.10.1/bin

Windows

Download the MSI installer from the official MongoDB downloads page and run it. Alternatively, use Chocolatey:

choco install mongosh

Core Concepts

  • Databases: A MongoDB instance can host multiple databases. You switch between them using use <database_name>.
  • Collections: Within a database, data is organized into collections, analogous to tables in relational databases.
  • Documents: Collections contain documents, which are BSON (Binary JSON) objects. These are the fundamental units of data.
  • db object: In mongosh, db is a global variable representing the current database you are connected to.
  • sh object: Used for managing sharded clusters (e.g., sh.status(), sh.enableSharding("mydb")).

Commands / Usage

Connecting to MongoDB

  • Default local instance (port 27017):

    mongosh
    

    Connects to mongodb://localhost:27017/.

  • Specify host and port:

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

    Connects to mongodb://atlas.example.com:27017/.

  • Connect to a specific database:

    mongosh "mongodb://localhost:27017/mydatabase"
    

    Connects to the mydatabase database on the local instance.

  • Connect with authentication:

    mongosh "mongodb://myuser:mypassword@localhost:27017/admin"
    

    Connects to the admin database with username myuser and password mypassword.

  • Connect to MongoDB Atlas:

    mongosh "mongodb+srv://my-cluster.mongodb.net/mydatabase?retryWrites=true&w=majority"
    

    Connects to a MongoDB Atlas cluster using the SRV record. You’ll be prompted for credentials if not provided in the URI.

Database Operations

  • List all databases:

    show dbs
    

    Displays a list of all databases on the server.

  • Switch to a database:

    use mydatabase
    

    Switches the current database context to mydatabase. If it doesn’t exist, it will be created when you first insert data.

  • Get current database:

    db
    

    Returns the Database object for the current database.

  • Drop the current database:

    db.dropDatabase()
    

    Deletes the current database. Use with extreme caution.

Collection Operations

  • List all collections in the current database:

    show collections
    

    Displays a list of all collections in the currently selected database.

  • Create a collection (implicitly):

    db.mycollection.insertOne({ name: "example" })
    

    Creates mycollection if it doesn’t exist and inserts a document.

  • Create a collection (explicitly):

    db.createCollection("mycappedcollection", { capped: true, size: 10240 })
    

    Creates a capped collection named mycappedcollection with a maximum size of 10240 bytes.

  • Rename a collection:

    db.oldname.renameCollection("newname")
    

    Renames oldname to newname.

  • Drop a collection:

    db.mycollection.drop()
    

    Deletes mycollection and all its documents.

Document Operations (CRUD)

Insert

  • Insert a single document:

    db.users.insertOne({ name: "Alice", age: 30, city: "New York" })
    

    Inserts one document into the users collection.

  • Insert multiple documents:

    db.users.insertMany([
      { name: "Bob", age: 25, city: "London" },
      { name: "Charlie", age: 35, city: "Paris" }
    ])
    

    Inserts an array of documents into the users collection.

Query (Find)

  • Find all documents in a collection:

    db.users.find()
    

    Retrieves all documents from the users collection.

  • Find documents matching a query filter:

    db.users.find({ city: "New York" })
    

    Finds all users located in "New York".

  • Find with projection (selecting fields):

    db.users.find({ city: "London" }, { name: 1, age: 1, _id: 0 })
    

    Finds users in "London" and returns only their name and age, excluding _id.

  • Find one document:

    db.users.findOne({ name: "Alice" })
    

    Retrieves the first document matching the criteria.

  • Find with comparison operators:

    db.users.find({ age: { $gt: 30 } })
    

    Finds users older than 30. ($gt = greater than).

  • Find with logical operators:

    db.users.find({ $or: [ { city: "New York" }, { age: { $lt: 20 } } ] })
    

    Finds users who are either in "New York" OR younger than 20.

  • Pretty print results:

    db.users.find().pretty()
    

    Formats the output of find() for better readability.

Update

  • Update a single document (first match):

    db.users.updateOne({ name: "Alice" }, { $set: { age: 31, status: "active" } })
    

    Updates the age to 31 and adds a status field for the first user named "Alice".

  • Update multiple documents:

    db.users.updateMany({ city: "London" }, { $set: { country: "UK" } })
    

    Adds a country field set to "UK" for all users in "London".

  • Replace a document (entirely):

    db.users.replaceOne({ name: "Bob" }, { name: "Robert", age: 26, city: "London" })
    

    Replaces the entire document for "Bob" with a new document. Use with care.

  • Increment a field:

    db.users.updateOne({ name: "Charlie" }, { $inc: { age: 1 } })
    

    Increments the age of "Charlie" by 1.

Delete

  • Delete a single document (first match):

    db.users.deleteOne({ name: "Alice" })
    

    Removes the first document found matching the criteria.

  • Delete multiple documents:

    db.users.deleteMany({ city: "Paris" })
    

    Removes all documents where the city is "Paris".

  • Delete all documents in a collection:

    db.users.deleteMany({})
    

    Removes all documents from the users collection.

Aggregation Framework

  • Basic aggregation pipeline:
    db.orders.aggregate([
      { $match: { status: "A" } },
      { $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } },
      { $sort: { totalAmount: -1 } }
    ])
    
    Finds orders with status "A", groups them by customerId summing the amount, and sorts by the total amount descending.

Indexing

  • Create an index:

    db.users.createIndex({ email: 1 })
    

    Creates an ascending index on the email field. 1 for ascending, -1 for descending.

  • Create a compound index:

    db.users.createIndex({ city: 1, age: -1 })
    

    Creates an index on city (ascending) and age (descending).

  • List all indexes:

    db.users.getIndexes()
    

    Shows all indexes on the users collection.

  • Drop an index:

    db.users.dropIndex("email_1")
    

    Drops the index named email_1.

Utility Commands

  • Display server status:

    db.serverStatus()
    

    Shows detailed information about the MongoDB server.

  • Display database statistics:

    db.stats()
    

    Shows statistics for the current database.

  • Display collection statistics:

    db.users.stats()
    

    Shows statistics for the users collection.

  • Run a command directly:

    db.runCommand({ buildInfo: 1 })
    

    Executes a specific MongoDB command.

  • Exit the shell:

    exit
    

    or press Ctrl+D.

Common Patterns

  • Find and update in one step (atomically):

    db.collection.findOneAndUpdate({ _id: ObjectId("...") }, { $set: { status: "processed" } }, { returnDocument: "after" })
    

    Finds a document by _id, updates it, and returns the new version of the document. Use returnDocument: "before" to get the original.

  • Piping output to a file:

    db.users.find({ age: { $gt: 25 } }).forEach(printjson) > users_over_25.json
    

    Finds users older than 25 and saves their JSON representation to a file. printjson is a mongosh helper.

  • Importing data from JSON:

    mongoimport --db mydatabase --collection mycollection --file data.json
    

    (This is a mongosh external command, not run inside the shell itself).

  • Exporting data to JSON:

    mongoexport --db mydatabase --collection mycollection --out data.json
    

    (External command).

  • Finding documents with missing fields:

    db.collection.find({ optionalField: { $exists: false } })
    

    Finds documents that do not have the optionalField.

  • Finding documents with specific array elements:

    db.inventory.find({ tags: { $in: ["camera", "electronics"] } })
    

    Finds inventory items tagged with either "camera" or "electronics".

  • Updating array elements:

    db.products.updateOne({ _id: 1 }, { $push: { sizes: "XL" } })
    

    Adds "XL" to the sizes array in the product with _id: 1.

Gotchas

  • _id is always unique: MongoDB automatically adds an _id field to every document if you don’t provide one, and it must be unique within a collection.
  • updateOne and updateMany default behavior: By default, updateOne and updateMany do not return the modified document. You need to use options like returnDocument: "after" (for findOneAndUpdate) or check the result object for modifiedCount.
  • Implicit collection creation: Collections are created automatically the first time you insert a document into them. Running db.createCollection() is usually only needed for specific options like capping.
  • use <db> doesn’t create the database immediately: The database is only truly created when you first insert data into a collection within it.
  • JavaScript context: mongosh runs JavaScript. Be mindful of JavaScript’s type coercion and truthiness rules.
  • ObjectId generation: When querying by _id, ensure you use the ObjectId() constructor: db.collection.find({ _id: ObjectId("507f1f77bcf86cd799439011") }). Simply using the string might not match.
  • mongosh vs. legacy mongo shell: mongosh is the successor to the older mongo shell. While largely compatible, mongosh offers improved performance, better JavaScript support, and features like connection string parsing. Always prefer mongosh for new work.
  • Command vs. Shell Methods: Some operations are executed as database commands (e.g., db.runCommand({ aggregate: "mycollection", pipeline: [...] })), while others are shell methods (e.g., db.mycollection.aggregate([...])). Shell methods are generally preferred for their readability.