How do you query MongoDB with filters, projections, sorting and limits?
BeginnerHands-onMongoDB
Answer
Short answer
db.collection.find(filter, projection) with query operators ($gt, $in, $regex…) for the filter, a projection to choose fields, then chain .sort(), .limit() and .skip().
Examples
// equality and nested fields
db.customers.find({ "address.city": "Pune" })
// comparison
db.orders.find({ total: { $gte: 1000, $lt: 50000 } })
// in a list, not equal, exists
db.orders.find({ status: { $in: ["NEW", "PROCESSING"] } })
db.orders.find({ couponCode: { $exists: true } })
// OR
db.orders.find({ $or: [{ status: "FAILED" }, { total: { $gt: 100000 } }] })
// arrays
db.customers.find({ tags: "vip" }) // array contains "vip"
db.customers.find({ tags: { $all: ["vip", "early"] } })
// projection, sort, limit
db.orders.find({ status: "NEW" }, { _id: 0, item: 1, total: 1 })
.sort({ createdAt: -1 })
.limit(10)
SQL comparison
SELECT item, total FROM orders WHERE status = 'NEW' ORDER BY created_at DESC LIMIT 10;
What to say in the interview
"find takes a filter and projection; operators like $gte, $in, $or and $exists build conditions, dot notation reaches nested fields, and sort/limit control results. It maps closely to SELECT ... WHERE ... ORDER BY ... LIMIT."