mongosh: The MongoDB Shell
Get fluent in mongosh — connect, switch databases, insert and query documents, run JavaScript files, aggregate, index, and shape the shell to your taste.
mongosh is the JavaScript shell that ships with MongoDB, and it is nothing like a SQL prompt. You call methods on a `db` object, results come back as live JavaScript objects, and the same expressions you type interactively can be saved as `.js` files and run unchanged. We start from an empty prompt and build real fluency one small thing at a time: switching databases, inserting and reading documents, sorting and updating, aggregating to answer real questions, adding indexes and reading an execution plan, and finally driving the shell non-interactively and customising it. Writing a query and running it are taught as separate things, so each idea lands on its own.
What you'll build
- Connect with mongosh and move between databases
- Insert documents and read them back with find and projections
- Sort, limit, update and delete documents
- Aggregate with $group, $match, $sort and $lookup
- Add indexes and read an execution plan
- Run mongosh non-interactively and customise it with .mongoshrc.js
Contents
- Open the shell
- Check the server version
- Switch to your database
- Confirm where you are
- List the databases
- List the collections
- Insert your first document
- Write a seed file
- Load the seed file
- Read a collection
- Remove the stray document
- Filter with a query
- Pick one, choose its fields
- Count documents
- Sort and limit
- Compare with an operator
- Update a field
- Delete a document
- Put it back
- Group and sum
- Filter, then sort the pipeline
- Join with $lookup
- Create a unique index
- List the indexes
- Read an execution plan
- Use a JavaScript variable
- Save a query to a file
- Run the saved query
- One value for a script
- Export to CSV
- Write a report script
- Run the report non-interactively
- Write a startup file
- See it take effect