QA
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→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?