Using Variables in the Shell — MongoDB Technical Interview Questions & Answers

Storing query results in shell variables for reuse.

Using Variables in the Shell

  • Simple meaning: mongosh is JavaScript. You can store results in const / let.
  • How to use: const asha = db.students.findOne({ roll: 12 }); asha.marks;
  • Cursors: const c = db.students.find(); c.next();
  • Try this: save findOne in a variable, print one field.
  • Common mistake: expecting SQL DECLARE. It is JS in the shell.
  • Interview tip: Shell is a JS REPL connected to MongoDB.

Technical Interview Tip: Store findOne in a variable and read a field.

Code Examples for Using Variables in the Shell

Using Variables in the Shell — working example

mongosh "mongodb://localhost:27017/prep_pilot"
const ada = db.users.findOne({ email: "ada@example.com" })
ada.skills
db.users.find({ city: ada.city })

Using Variables in the Shell — mongosh is the modern MongoDB shell; you can store query results in variables.

How to Explain Using Variables in the Shell to an Interviewer

Can you use variables in mongosh?

Yes — it is a JavaScript shell