Beginner LevelMongoDB & Mongoose
How do you query array fields in MongoDB using $elemMatch and $all?
❓ Interview Prompt: Explain querying array fields, matching exact array items, $all (matches all elements), and $elemMatch (multi-condition array matching).
Querying array fields requires specialized operators:
•
Direct Array Match: '{ tags: "tech" }' matches documents where "tech" exists anywhere in the tags array.
•
'$all': '{ tags: { $all: ["node", "mongodb"] } }' matches documents containing EVERY specified element.
•
'$elemMatch': Requires a single array element to satisfy all specified conditions simultaneously!
Code Implementation Example
typescript
import { StudentModel } from './models/Student';
async function findHighAchievers() {
// Find students with at least ONE test score > 90 in Math
const students = await StudentModel.find({
grades: {
$elemMatch: { subject: 'Math', score: { $gte: 90 } }
}
});
return students;
}💡Querying complex embedded array objects using $elemMatch.
🎯 Interview Key Takeaway
Use $elemMatch when querying array objects to ensure a single element satisfies multiple conditions simultaneously.
#$elemMatch#$all#Array Queries#Beginner
Back to all MongoDB & Mongoose Questions→