$in and $nin — MongoDB Technical Interview Questions & Answers

Matching a field against a list of possible values.

$in and $nin

  • Simple meaning: $in matches if the field is one of a list. $nin is “none of these”.
  • How to use: db.students.find({ city: { $in: ["Pune", "Delhi"] } }). $nin: { city: { $nin: ["Pune"] } }.
  • Try this: three cities, find two of them with $in.
  • Common mistake: $in with a single value when you meant $eq. $in wants an array.
  • Interview tip: “SQL IN list” → $in. Show the array.

Technical Interview Tip: $in takes an array of allowed values.

Code Examples for $in and $nin

$in and $nin — working example

db.users.find({ city: { $in: ["Pune", "Mumbai", "Delhi"] } })
db.users.find({ role: { $nin: ["banned", "guest"] } })

$in and $nin — $in matches any value in a list; $nin matches when the value is not in the list.

How to Explain $in and $nin to an Interviewer

What is $in?

Match field against a list { city: { $in: ["Pune", "Delhi"] } }