0
0
MongoDBquery~5 mins

Array expressions ($size, $arrayElemAt, $filter) in MongoDB

Choose your learning style9 modes available
Introduction

Array expressions help you work with lists inside your data. They let you count items, pick specific items, or find items that match a rule.

You want to count how many items are in a list inside your data.
You need to get a specific item from a list by its position.
You want to find only the items in a list that meet a certain condition.
Syntax
MongoDB
db.collection.aggregate([
  {
    $project: {
      totalItems: { $size: "$arrayField" },
      firstItem: { $arrayElemAt: ["$arrayField", 0] },
      filteredItems: {
        $filter: {
          input: "$arrayField",
          as: "item",
          cond: { /* <condition using $$item> */ }
        }
      }
    }
  }
])

$size counts how many elements are in an array.

$arrayElemAt gets the element at the given index (starting at 0).

$filter returns a new array with only elements that match the condition.

Examples
This counts how many tags each product has.
MongoDB
db.products.aggregate([
  { $project: { numberOfTags: { $size: "$tags" } } }
])
This gets the first tag from the tags array.
MongoDB
db.products.aggregate([
  { $project: { firstTag: { $arrayElemAt: ["$tags", 0] } } }
])
This finds tags that are exactly "expensive".
MongoDB
db.products.aggregate([
  {
    $project: {
      expensiveTags: {
        $filter: {
          input: "$tags",
          as: "tag",
          cond: { $eq: ["$$tag", "expensive"] }
        }
      }
    }
  }
])
Sample Program

This example inserts three orders with different items and prices. Then it counts how many items each order has, gets the first item, and filters prices greater than 1.

MongoDB
db.orders.insertMany([
  { _id: 1, items: ["apple", "banana", "orange"], prices: [1, 2, 3] },
  { _id: 2, items: ["bread"], prices: [2] },
  { _id: 3, items: [], prices: [] }
])

db.orders.aggregate([
  {
    $project: {
      totalItems: { $size: "$items" },
      firstItem: { $arrayElemAt: ["$items", 0] },
      expensivePrices: {
        $filter: {
          input: "$prices",
          as: "price",
          cond: { $gt: ["$$price", 1] }
        }
      }
    }
  }
])
OutputSuccess
Important Notes

$size returns 0 if the array is empty or missing.

$arrayElemAt returns null if the index is out of range.

$filter lets you use variables with $$ to refer to each item.

Counting items is fast, but filtering large arrays can be slower.

Summary

$size counts how many elements are in an array.

$arrayElemAt picks one element by its position.

$filter creates a smaller array with only items that match a rule.