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.
dbobject: Inmongosh,dbis a global variable representing the current database you are connected to.shobject: Used for managing sharded clusters (e.g.,sh.status(),sh.enableSharding("mydb")).
Commands / Usage
Connecting to MongoDB
-
Default local instance (port 27017):
mongoshConnects to
mongodb://localhost:27017/. -
Specify host and port:
mongosh --host atlas.example.com --port 27017Connects to
mongodb://atlas.example.com:27017/. -
Connect to a specific database:
mongosh "mongodb://localhost:27017/mydatabase"Connects to the
mydatabasedatabase on the local instance. -
Connect with authentication:
mongosh "mongodb://myuser:mypassword@localhost:27017/admin"Connects to the
admindatabase with usernamemyuserand passwordmypassword. -
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 dbsDisplays a list of all databases on the server.
-
Switch to a database:
use mydatabaseSwitches the current database context to
mydatabase. If it doesn’t exist, it will be created when you first insert data. -
Get current database:
dbReturns the
Databaseobject 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 collectionsDisplays a list of all collections in the currently selected database.
-
Create a collection (implicitly):
db.mycollection.insertOne({ name: "example" })Creates
mycollectionif it doesn’t exist and inserts a document. -
Create a collection (explicitly):
db.createCollection("mycappedcollection", { capped: true, size: 10240 })Creates a capped collection named
mycappedcollectionwith a maximum size of 10240 bytes. -
Rename a collection:
db.oldname.renameCollection("newname")Renames
oldnametonewname. -
Drop a collection:
db.mycollection.drop()Deletes
mycollectionand 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
userscollection. -
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
userscollection.
Query (Find)
-
Find all documents in a collection:
db.users.find()Retrieves all documents from the
userscollection. -
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
nameandage, 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
statusfield for the first user named "Alice". -
Update multiple documents:
db.users.updateMany({ city: "London" }, { $set: { country: "UK" } })Adds a
countryfield 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
cityis "Paris". -
Delete all documents in a collection:
db.users.deleteMany({})Removes all documents from the
userscollection.
Aggregation Framework
- Basic aggregation pipeline:
Finds orders with status "A", groups them bydb.orders.aggregate([ { $match: { status: "A" } }, { $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } }, { $sort: { totalAmount: -1 } } ])customerIdsumming theamount, and sorts by the total amount descending.
Indexing
-
Create an index:
db.users.createIndex({ email: 1 })Creates an ascending index on the
emailfield.1for ascending,-1for descending. -
Create a compound index:
db.users.createIndex({ city: 1, age: -1 })Creates an index on
city(ascending) andage(descending). -
List all indexes:
db.users.getIndexes()Shows all indexes on the
userscollection. -
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
userscollection. -
Run a command directly:
db.runCommand({ buildInfo: 1 })Executes a specific MongoDB command.
-
Exit the shell:
exitor 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. UsereturnDocument: "before"to get the original. -
Piping output to a file:
db.users.find({ age: { $gt: 25 } }).forEach(printjson) > users_over_25.jsonFinds users older than 25 and saves their JSON representation to a file.
printjsonis amongoshhelper. -
Importing data from JSON:
mongoimport --db mydatabase --collection mycollection --file data.json(This is a
mongoshexternal 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
sizesarray in the product with_id: 1.
Gotchas
_idis always unique: MongoDB automatically adds an_idfield to every document if you don’t provide one, and it must be unique within a collection.updateOneandupdateManydefault behavior: By default,updateOneandupdateManydo not return the modified document. You need to use options likereturnDocument: "after"(forfindOneAndUpdate) or check the result object formodifiedCount.- 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:
mongoshruns JavaScript. Be mindful of JavaScript’s type coercion and truthiness rules. ObjectIdgeneration: When querying by_id, ensure you use theObjectId()constructor:db.collection.find({ _id: ObjectId("507f1f77bcf86cd799439011") }). Simply using the string might not match.mongoshvs. legacymongoshell:mongoshis the successor to the oldermongoshell. While largely compatible,mongoshoffers improved performance, better JavaScript support, and features like connection string parsing. Always prefermongoshfor 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.