mongosh is the interactive shell for MongoDB. JavaScript expressions control flow; database methods live on db.
Connection and help
// Shell:
mongosh 'mongodb://localhost:27017/practice'
// Inside mongosh:
help
db.help()
db.products.help()Practice: Run in mongosh on your practice database.
Switching context
show dbs
use practice
db.getName()
db.stats()
Running queries
const cursor = db.products.find({ price: { $gte: 10 } })
cursor.toArray()
cursor.count()In apps, use drivers with async APIs; mongosh is for learning and ops.
Important interview questions and answers
- Q: db vs database name?
A: db is the current database handle—methods like find run on collections. - Q: Semicolon in mongosh?
A: Often optional for one-liners; use when chaining multiple statements.
Self-check
- How do you switch databases?
- What object exposes collection methods?
Pitfall: Wrong database context—always check db.getName() before destructive ops.
Interview prep
- db object?
- Handle for current database; exposes collection methods.
- use practice?
- Switches database context for subsequent commands.