Skip to content

$indexOfArray

The $indexOfArray operator returns the index of the first occurrence of a value in an array.


📌 Syntax

{ "$indexOfArray": [ <arrayExpression>, <searchValue>, <start>, <end> ] }
  • arrayExpression: The array to search
  • searchValue: The value to search for
  • start: (optional) Index to start searching from
  • end: (optional) Index to end searching (exclusive)

✅ Base Example – Find Index of Value

📥 Input Document

{ "tags": ["sale", "new", "hot"] }

📌 Expression

{ "$indexOfArray": ["$tags", "new"] }

📤 Output

1

✅ Base Example – Value Not Found

📥 Input Document

{ "tags": ["sale", "hot"] }

📌 Expression

{ "$indexOfArray": ["$tags", "exclusive"] }

📤 Output

-1

🧱 Ecommerce Example – Position of Top-Selling Product

📌 Pipeline

[
  {
    "$project": {
      "productRank": {
        "$indexOfArray": ["$topProducts", "SKU-1002"]
      }
    }
  }
]

📥 Input Document

{
  "topProducts": ["SKU-1001", "SKU-1002", "SKU-1003"]
}

📤 Output

{ "productRank": 1 }

🔧 Common Use Cases

  • Determine item positions
  • Ranking systems
  • Validation of list order

  • $arrayElemAt, $slice, $filter, $indexOfBytes, $indexOfCP

🧠 Notes

  • Returns -1 if not found.
  • Use with $cond to handle missing values gracefully.