The MongoDB command line interface (CLI) allows you to interact with MongoDB databases from a terminal or command prompt, without using a GUI application. For many tasks, the CLI can be faster and more convenient than a graphical tool. This guide covers the basics of using MongoDB shell.
Installing the MongoDB CLI
To install the CLI shell on your system:
- Navigate to the MongoDB downloads page and select the appropriate package for your operating system. Generally this will be mongosh for modern systems.
-
Extract the archive file to your desired location. For example
C:\Program Fileson Windows or/usr/local/binon Linux/macOS. - Add the binary path to your system path to access it globally:
# Linux/macOS
export PATH=~/path/to/mongosh-1.6.1-linux-x64/bin:$PATH
# Windows Powershell
$env:Path += ";C:\Path\To\mongosh-1.6.1-win32-x64\bin"
- Verify installation with
mongosh --version
Connecting to MongoDB
To connect to the default MongoDB server running on localhost port 27017:
mongosh
To connect to a MongoDB database hosted elsewhere, provide a connection string using the --host option:
mongosh --host "mongodb+srv://user:[email protected]/test"
Basic CLI Commands
show dbs– Show database namesuse mydb– Switch current database tomydbshow collections– Show collections in current databasedb.mycoll.insert({...})– Insert a document intomycollcollectiondb.mycoll.find()– Display documents inmycollcollectiondb.mycoll.update(...)– Update documents inmycolldb.mycoll.remove(...)– Delete matching documents
Querying Data
The .find() method supports rich querying over documents using operators like:
- Comparison (
$eq,$gt,$lt, etc.) - Logical (
$and,$or,$not) - Element (
$exists,$type) - Evaluation (
$expr,$jsonSchema)
For example, getting all documents where age is greater than 18:
db.users.find({age: { $gt: 18}})
Indexes
Indexes can greatly improve query performance. To create an index on the name field:
db.users.createIndex({name: 1})
Analyze a query explains to review index usage:
db.users.find({age: 20}).explain()
Import/Export
The mongodump and mongorestore utilities can import/export data between MongoDB databases and files.
Export a collection to JSON files:
mongodump --db test --collection mycoll
Import data from BSON files:
mongorestore --db newdb --collection imported dump/test/mycoll.bson
Admin Commands
Admin commands provide insight into database operations:
db.stats()– Get storage statisticsdb.serverStatus()– Get server overviewshow users– Show user accountsshow profiles– Show most recent operations
Best Practices
- Format outputs using
.pretty()for enhanced readability - Test queries on small result sets before running on full collections
- Explore JS capabilities of the shell like variables and control flow
Hopefully this overview gives you a taste of how powerful the MongoDB CLI can be! Let me know if you have any other questions.



