← All bricks

mongosh · Beginner

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

  1. Open the shell
  2. Check the server version
  3. Switch to your database
  4. Confirm where you are
  5. List the databases
  6. List the collections
  7. Insert your first document
  8. Write a seed file
  9. Load the seed file
  10. Read a collection
  11. Remove the stray document
  12. Filter with a query
  13. Pick one, choose its fields
  14. Count documents
  15. Sort and limit
  16. Compare with an operator
  17. Update a field
  18. Delete a document
  19. Put it back
  20. Group and sum
  21. Filter, then sort the pipeline
  22. Join with $lookup
  23. Create a unique index
  24. List the indexes
  25. Read an execution plan
  26. Use a JavaScript variable
  27. Save a query to a file
  28. Run the saved query
  29. One value for a script
  30. Export to CSV
  31. Write a report script
  32. Run the report non-interactively
  33. Write a startup file
  34. See it take effect