How do you run MongoDB, log in and work with data?

BeginnerHands-onMongoDB
Answer

Short answer

Run MongoDB in Docker, connect with the mongosh shell, and use commands like show dbs, use, insertOne, find, updateOne and deleteOne.

Step by step

docker run -d --name mongo \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD='Mongo@123' \
  -p 27017:27017 \
  -v mongo-data:/data/db \
  mongo:7

docker exec -it mongo mongosh -u admin -p --authenticationDatabase admin
# or from your machine:
mongosh "mongodb://admin:Mongo%40123@localhost:27017/?authSource=admin"

Inside mongosh:

show dbs                        // list databases
use shop                        // switch (creates it when you first insert data)
show collections                // list collections

db.customers.insertOne({ name: "Aditya", city: "Gurugram", orders: 3 })
db.customers.insertMany([{ name: "Priya", city: "Pune" }, { name: "Rahul", city: "Delhi" }])

db.customers.find()                              // all documents
db.customers.find({ city: "Pune" })              // filter
db.customers.find({ orders: { $gt: 2 } })        // orders greater than 2
db.customers.countDocuments()

db.customers.updateOne({ name: "Priya" }, { $set: { city: "Mumbai" } })
db.customers.deleteOne({ name: "Rahul" })

Create a user for an application:

use shop
db.createUser({ user: "orders_app", pwd: "Str0ng#Pass", roles: [{ role: "readWrite", db: "shop" }] })

Backup and restore:

mongodump --uri "mongodb://admin:Mongo%40123@localhost:27017/?authSource=admin" --db shop --out /backup/
mongorestore --uri "mongodb://admin:Mongo%40123@localhost:27017/?authSource=admin" /backup/

What to say in the interview

"I run MongoDB in Docker with root credentials and a volume, and connect with mongosh. I use show dbs and use to navigate, insertOne and find to add and read documents, updateOne with $set to change fields, and deleteOne to remove them. Each app gets its own user with the readWrite role on its database. Backups are done with mongodump and mongorestore, or managed snapshots in MongoDB Atlas."

Follow-up questions you may get

  • Why %40 in the connection string? Special characters like @ in passwords must be URL-encoded inside a URI.
  • What is authSource=admin? It tells MongoDB which database stores the user's credentials.
All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB