Introduction
The $size operator helps you find out how many items are in an array inside your data. It tells you the length of the array.
Jump into concepts and practice - no test required
{ $size: <array> }{ $size: "$hobbies" }{ $size: "$tags" }{ $size: "$orders.items" }db.users.insertMany([
{ name: "Alice", hobbies: ["reading", "swimming", "coding"] },
{ name: "Bob", hobbies: ["gaming"] },
{ name: "Charlie", hobbies: [] }
])
// Find users and show how many hobbies they have
const cursor = db.users.aggregate([
{
$project: {
name: 1,
hobbiesCount: { $size: "$hobbies" }
}
}
])
cursor.forEach(doc => printjson(doc))$size operator do in MongoDB?$size$size operator is used to count how many elements are inside an array field in a MongoDB document.$size does.$size = count array elements [OK]$size in a MongoDB aggregation pipeline to add a field itemCount that counts elements in the items array?$size operator is used inside an expression to count array elements. It must be inside a stage like $addFields or $project with the array field referenced as "$items".$length. { $project: { itemCount: { $size: "items" } } } misses the $ before items. { $match: { itemCount: { $size: "$items" } } } misuses $match with $size.{ "name": "Alice", "tags": ["red", "blue"] }{ "name": "Bob", "tags": ["green"] }{ "name": "Carol", "tags": [] }[{ $project: { name: 1, tagCount: { $size: "$tags" } } }]$size counts how many items are in the tags array: Alice has 2, Bob has 1, Carol has 0.name and adds tagCount with the counted size.{ $match: { tags: { $size: 3 } } }$size inside $match like this is invalid because $size is an aggregation expression, not a query operator.$expr with $size, like: { $match: { $expr: { $eq: [ { $size: "$tags" }, 3 ] } } }.comments array has more than 2 elements. Which aggregation pipeline stage correctly filters these documents?$expr to allow aggregation expressions inside $match.{ $gt: [ { $size: "$comments" }, 2 ] } inside $expr.$expr, misuse $size placement, or have wrong syntax for $gt.