How do you query documents in MongoDB?
Why Interviewers Ask This
This is a classic screening question for MongoDB roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
MongoDB's find() method retrieves documents matching a query filter: db.collection.find(query, projection). find() examples: All documents: db.users.find({}); Exact match: db.users.find({ name: "Alice" }); Multiple conditions (implicit AND): db.users.find({ name: "Alice", age: 30 }); Projection (include/exclude fields): db.users.find({}, { name: 1, email: 1, _id: 0 }) — 1 = include, 0 = exclude, can't mix includes and excludes (except _id). findOne(): returns the first matching document (or null). Query operators: Comparison: $eq, $ne, $gt, $gte, $lt, $lte — db.users.find({ age: { $gte: 18, $lt: 65 } }); $in: db.users.find({ status: { $in: ["active", "pending"] } }); $nin: not in list; Logical: $and, $or, $not, $nor; Element: $exists, $type; Evaluation: $regex, $expr, $where; Array: $all, $elemMatch, $size. Sorting: .sort({ age: 1 }) (1 ascending, -1 descending). Limiting and skipping: .limit(10).skip(20) — page 3 of 10. Count: db.users.countDocuments({ active: true }).
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a MongoDB codebase.