Use $elemMatch to find documents where at least one item in an array matches multiple conditions together. It helps when you want to check several things about the same array element.
$elemMatch for complex array queries in MongoDB
db.collection.find({ arrayField: { $elemMatch: { condition1, condition2, ... } } })$elemMatch applies multiple conditions to the same array element, not different elements.
Without $elemMatch, conditions on array fields check elements independently, which can give wrong results.
db.users.find({ skills: { $elemMatch: { name: "JavaScript", level: { $gte: 3 } } } })db.orders.find({ products: { $elemMatch: { price: { $gt: 100 }, quantity: { $gt: 2 } } } })db.posts.find({ comments: { $elemMatch: { user: "alice", text: /mongodb/i } } })db.addresses.find({ locations: { $elemMatch: { city: "New York", zip: "10001" } } })This inserts three users with different skills. Then it finds users who have at least one skill named "JavaScript" with level 3 or more. It prints the matching users.
db.users.insertMany([
{ name: "John", skills: [ { name: "JavaScript", level: 2 }, { name: "Python", level: 4 } ] },
{ name: "Jane", skills: [ { name: "JavaScript", level: 5 }, { name: "C++", level: 3 } ] },
{ name: "Doe", skills: [ { name: "Java", level: 1 } ] }
])
// Find users with JavaScript skill level 3 or higher
const result = db.users.find({ skills: { $elemMatch: { name: "JavaScript", level: { $gte: 3 } } } }).toArray()
printjson(result)Time complexity: Depends on indexes and array size; using indexes on array fields can speed up queries.
Space complexity: Minimal extra space; query only filters documents.
Common mistake: Forgetting $elemMatch and writing conditions that apply to different array elements separately, causing wrong matches.
Use $elemMatch when you want all conditions to apply to the same array element. Use separate conditions without $elemMatch when conditions can apply to different elements.
$elemMatch helps find array elements matching multiple conditions together.
It ensures all conditions apply to the same element, avoiding false matches.
Use it for complex queries on arrays with multiple criteria.