Connecting with mongosh

MongoDB · Essentials · 8 min

mongosh is the quickest way to explore data, try queries and administer a deployment.

mongosh is the MongoDB Shell, a Node.js-based REPL. Start it with a connection string: mongosh "mongodb://localhost:27017" for a local server or mongosh "mongodb+srv://cluster0.example.mongodb.net/" --username ana for Atlas.

A few shell helpers get you oriented:

  • show dbs lists databases, use shop switches to (or lazily creates) the shop database,
  • show collections lists collections in the current database,
  • db is the current database object, and db.orders is the orders collection.

A database or collection is created the first time you write to it, so use typo followed by a find just returns nothing rather than an error. Watch for spelling mistakes.

Because the shell is JavaScript, you can use variables, loops and functions: const cutoff = new Date("2026-01-01") and then pass cutoff in a query. Query results are cursors; the shell prints the first batch (20 documents) and you type it to see more. .toArray() collects everything, which is fine for small results.

Use db.orders.help() or tab completion to discover methods, and exit to leave. In production scripts you'll use a driver instead, but the query syntax you learn here is nearly identical.

Example

// $ mongosh "mongodb://localhost:27017"
show dbs                    // admin, config, local, ...
use shop                    // switched to db shop
db.orders.insertOne({ status: "new", total: 12 })
show collections            // orders  (created by the first write)
const big = db.orders.find({ total: { $gt: 10 } }).toArray()
big.length                  // 1
db.orders.countDocuments()  // 1
db.getName()                // shop

Remember

  • mongosh is a JavaScript REPL: use, show dbs, show collections, db.<coll>
  • Databases and collections are created on first write
  • find returns a cursor; type it for the next batch

Watch out for

  • Misspelling a collection name: you silently query an empty, nonexistent collection.

Check yourself

  1. You run use reports in mongosh but never insert anything. What happens?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.mongodb.com/docs/mongodb-shell/