$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 searchsearchValue: The value to search forstart: (optional) Index to start searching fromend: (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
🔗 Related Operators
$arrayElemAt,$slice,$filter,$indexOfBytes,$indexOfCP
🧠Notes
- Returns
-1if not found. - Use with
$condto handle missing values gracefully.