Learn mongosh: A Hands-On Tutorial You Can Run in Your Browser
Learn the MongoDB shell by running it: find, update, aggregate and check indexes in live shells on this page, with nothing to install.
mongosh is the MongoDB shell: you type a command, and MongoDB answers. The quickest way to learn it is to run commands and look at what comes back, so this post has working shells in it. You don't need to install anything.
Each shell below runs in your browser on a small sample shop with products, customers, and orders. They all share one database, so a change in one shows up in the next. Nothing you do reaches a real server, so feel free to break things. Reloading the page starts over.
To run code, press Run, or ⌘ Enter on a Mac and Ctrl Enter elsewhere. You can also run just the statement you selected. The shells take a moment to load the first time.
Look around first
Before you query a database, find out what is in it. db is the database you are in, getCollectionNames() lists its collections, and findOne() shows you one document so you know the field names.
In a product, you will see a text field (name), a decimal (price), a list (tags) and a list of objects (stock). Each type gets queried a little differently.
Find documents
find() takes a filter. Fields in the same filter are combined with AND.
db.orders.find({ status: "delivered" })Comparisons use operators: $gt, $gte, $lt, $lte, $ne and $in. The second argument picks which fields come back, and sort() and limit() shape the list. In a sort, 1 is ascending and -1 is descending.
Try it: change the first query to show products that cost 50 or more.
Query lists and nested fields
To match a value inside a list, write it as if the field were a single value. To reach inside an object, use a dot, and put the path in quotes.
Be careful with lists of objects. If two conditions must hold for the same item, use $elemMatch. Without it, one item can satisfy the first condition and another item the second. Compare the two counts here:
Insert, update, delete
insertOne() adds a document. updateOne() takes a filter and a change: $set writes a field, $inc adds to a number, and $push appends to a list. deleteOne() removes the first match.
Read what each command returns. matchedCount: 0 means your filter found nothing, which is easy to miss because it is not an error.
On a real database, run find() with your filter before you put it in updateMany() or deleteMany(). An empty filter, {}, matches every document.
Summarize with aggregate()
find() returns documents. For totals and averages, use aggregate(). It takes a list of stages, and each stage works on the output of the one before it. This pipeline keeps delivered orders, groups them by customer, and looks up each customer's name:
When a pipeline gives a result you did not expect, delete the last stage and run it again. Keep going until the output makes sense, and you have found the stage to fix.
mongosh is JavaScript
You can use variables, functions, and loops. toArray() turns a query result into a normal array.
This is handy for small jobs. On a large collection, let the database do the counting with aggregate() so you don't load every document into the shell.
Check whether a query uses an index
Without an index, MongoDB reads the whole collection to answer a filter. explain() tells you how many documents it read. Run this and compare the two numbers:
Run it a second time and the numbers will match, because the index is already there. db.orders.dropIndex("customerId_1") takes it away again.
Try it yourself
Write these in the empty shell. The answers are below it.
- List the names and prices of the five most expensive products.
- Count the gold customers.
- Find the average review rating of each product, highest first.
Show the answers
// 1
db.products.find({}, { _id: 0, name: 1, price: 1 }).sort({ price: -1 }).limit(5)
// 2
db.customers.countDocuments({ tier: "gold" })
// 3
db.reviews.aggregate([
{ $group: { _id: "$productId", average: { $avg: "$rating" }, reviews: { $sum: 1 } } },
{ $sort: { average: -1 } }
])
Use it on your own database
The shells on this page run Minileaf, our MongoDB-compatible engine, in your browser. To run mongosh against a real server, install it from MongoDB and pass your connection string:
mongosh "mongodb://localhost:27017/shop"In the terminal, show dbs lists the databases, use shop switches to one, and exit leaves.
For more practice, the MongoDB playground adds a query builder and an aggregation builder on the same kind of data, and the MongoDB interview questions check your answers for you.