mongodb 7.5.0MongoDB Array Query Examples
Query arrays in MongoDB with exact matches, any-element conditions, $all, $elemMatch, array indexes, projection, and aggregation without ambiguous results.
Prepare documents with scalar and object arrays
MongoDB can query arrays without first flattening them, but similar-looking predicates can express different requirements. The examples use products with an array of scalar tags and an array of embedded stock records:
const products = db.collection("array_query_products");
products.deleteMany({ tutorial: "arrays" });
products.insertMany([
{
sku: "KEY-75",
tags: ["keyboard", "wireless", "sale"],
stock: [
{ warehouse: "ist", quantity: 8 },
{ warehouse: "ams", quantity: 0 }
],
tutorial: "arrays"
},
{
sku: "MOUSE-01",
tags: ["mouse", "wireless"],
stock: [
{ warehouse: "ist", quantity: 0 },
{ warehouse: "ams", quantity: 14 }
],
tutorial: "arrays"
},
{
sku: "CABLE-02",
tags: ["cable", "usb-c"],
stock: [{ warehouse: "ist", quantity: 25 }],
tutorial: "arrays"
}
]);
Keep the tutorial marker in each query so the examples cannot select unrelated data.
Match one value anywhere in a scalar array
Equality against an array field matches when at least one element equals the value:
products.find({
tutorial: "arrays",
tags: "wireless"
});
This returns the keyboard and mouse. You do not need $elemMatch for one simple condition on a scalar array.
An exact-array query is different:
products.find({
tutorial: "arrays",
tags: ["mouse", "wireless"]
});
The field must equal that array with the same elements in the same order. Adding another tag or reversing the order prevents a match. Use exact-array equality only when order and complete membership are domain requirements.
Require several values with $all
Use $all when the array must contain every listed value but may also contain others:
products.find({
tutorial: "arrays",
tags: { $all: ["wireless", "sale"] }
});
Only the keyboard matches. The stored order does not need to match the query order. $all is useful for tag filters where selected tags are combined with AND semantics.
For OR semantics, use $in:
products.find({
tutorial: "arrays",
tags: { $in: ["sale", "usb-c"] }
});
This returns the keyboard and cable because each document contains at least one requested tag.
Use $elemMatch for related conditions on one object
Suppose the requirement is “stock in Istanbul with a quantity greater than zero.” Both conditions must apply to the same embedded array element:
products.find({
tutorial: "arrays",
stock: {
$elemMatch: {
warehouse: "ist",
quantity: { $gt: 0 }
}
}
});
The keyboard and cable match. $elemMatch prevents MongoDB from satisfying warehouse with one element and quantity with another.
The following query looks similar but has different semantics:
products.find({
tutorial: "arrays",
"stock.warehouse": "ist",
"stock.quantity": { $gt: 0 }
});
Each dotted condition can match a different element. The mouse has an Istanbul entry with zero stock and an Amsterdam entry with positive stock, so the independent predicates can make it match even though Istanbul has none. Use $elemMatch when conditions describe one logical array item.
Match array length deliberately
Use $size for an exact number of elements:
products.find({
tutorial: "arrays",
tags: { $size: 2 }
});
$size does not accept a range expression. For repeated queries such as “at least three tags,” consider maintaining a validated count field when that value is part of the domain and indexing requirements. Do not add derived fields merely for convenience without defining how every write keeps them correct.
Return only the relevant array element
Projection with $elemMatch can return the first matching embedded element:
products.findOne(
{ tutorial: "arrays", sku: "KEY-75" },
{ projection: { sku: 1, stock: { $elemMatch: { warehouse: "ist" } } } }
);
For transformations or multiple matching elements, use aggregation with $filter:
products.aggregate([
{ $match: { tutorial: "arrays" } },
{
$project: {
sku: 1,
available: {
$filter: {
input: "$stock",
as: "entry",
cond: { $gt: ["$$entry.quantity", 0] }
}
}
}
}
]);
Projection shapes the returned document; it does not change the stored array.
Index array queries and verify the plan
An index on an array field becomes multikey:
products.createIndex({ tags: 1 }, { name: "tags_lookup" });
Multikey indexes support many array predicates, but compound indexes involving multiple array fields have restrictions and can create many index entries. Design indexes from actual query shapes and data cardinality.
Run an important query with explain("executionStats"):
products.find({
tutorial: "arrays",
tags: "wireless"
}).explain("executionStats");
The tiny tutorial dataset is not a performance benchmark. Use representative staging data to compare keys examined, documents examined, returned records, and sort behavior.
Practice and cleanup
Add a product whose stock array has one Istanbul entry with zero quantity and one Amsterdam entry with positive quantity. Compare the dotted-field query with the $elemMatch query and explain the extra match. Then add a scalar tags value intentionally and observe how inconsistent schemas complicate expectations.
Remove the tutorial documents:
products.deleteMany({ tutorial: "arrays" });
Continue with general MongoDB query examples, schema validation, and aggregation pipeline examples.