0
0
MongoDBquery~5 mins

$size operator for array length in MongoDB

Choose your learning style9 modes available
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.
You want to count how many hobbies a person has in their profile.
You need to find products that have exactly 3 tags.
You want to filter orders that contain more than 5 items.
You want to check if a student's list of completed courses is empty or not.
Syntax
MongoDB
{ $size: <array> }
The must be a field that contains an array in your document.
You can use $size inside aggregation pipelines or queries to filter documents.
Examples
Counts the number of elements in the 'hobbies' array.
MongoDB
{ $size: "$hobbies" }
Returns the length of the 'tags' array.
MongoDB
{ $size: "$tags" }
Finds how many items are in the 'items' array inside 'orders'.
MongoDB
{ $size: "$orders.items" }
Sample Program
This program inserts three users with different numbers of hobbies. Then it uses $size to count hobbies for each user and shows the result.
MongoDB
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))
OutputSuccess
Important Notes
The $size operator runs in O(1) time because MongoDB stores array lengths internally.
If the field is not an array or is missing, $size throws an error in aggregation pipelines; in queries, it matches documents where the field is an array of the specified size.
Use $size when you want exact array length; for conditions like 'more than' or 'less than', combine with $expr and comparison operators.
Summary
$size tells you how many elements are in an array.
Use it to count items inside arrays in your documents.
Works well inside aggregation pipelines to create new fields or filter data.