MongoDB provides specialized operators for querying documents that contain arrays.
Matches arrays that contain all the specified elements (regardless of order).
// Find items where the tags array contains both "appliance" and "school"
db.products.find({ tags: { $all: ["appliance", "school"] } })The `$elemMatch` operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
// Find documents where at least one array element matches both criteria
db.survey.find({
results: {
$elemMatch: { product: "xyz", score: { $gte: 8 } }
}
})The `$size` operator matches any array with the number of elements specified by the argument.
// Find documents where the tags array has exactly 3 elements
db.products.find({ tags: { $size: 3 } })To query if an array contains at least one element with a certain value, you don't need a special operator.
// Find products where one of the tags is "red"
db.products.find({ tags: "red" })$size: { $gt: 5 }). For range queries on array lengths, you might need an alternative strategy like storing the length in a separate field.