How do you connect to MongoDB and explore databases and collections?

BeginnerHands-onMongoDB
Answer

Short answer

Use mongosh with a connection string, then show dbs, use <db>, show collections, and basic queries like db.<collection>.findOne() and countDocuments().

Connect

mongosh "mongodb://localhost:27017"
mongosh "mongodb://admin@localhost:27017/?authSource=admin"
mongosh "mongodb+srv://[email protected]/shop"      # Atlas
docker exec -it mongo mongosh -u admin -p --authenticationDatabase admin
kubectl exec -it mongo-0 -- mongosh

Explore

show dbs
use shop
show collections
db.orders.countDocuments()
db.orders.findOne()
db.orders.find().limit(5).pretty()
db.orders.getIndexes()
db.stats()                     // database size
db.orders.stats().size         // collection size in bytes
db.version()

What to say in the interview

"mongosh with a connection string including authSource, then show dbs, use, show collections, and quick checks like countDocuments, findOne and getIndexes. For Atlas it's a mongodb+srv URL."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB