The $indexOfArray operator finds the position of a value inside an array. It returns a zero-based index (like JavaScript’s indexOf) or -1 when the value is not found. Use it in aggregation pipelines to locate tags, statuses, or items in embedded arrays.
01
Array Index
Find a value’s position.
02
Syntax
Array, search, start, end.
03
$project Stage
Add computed index fields.
04
Not Found
Returns -1 on miss.
05
Use Cases
Tags, priorities, lookups.
06
Search Range
Optional start and end.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $indexOfArray operator searches an array for the first occurrence of a value and returns its zero-based index. For example, searching [ "js", "mongodb", "node" ] for "mongodb" returns 1. If the value is absent, the result is -1.
You can optionally pass start and end indexes to search only part of the array. This is useful when you need the position of a value after a certain point, or when working with sliced data.
💡
Beginner Tip
Think of $indexOfArray as MongoDB’s version of JavaScript’s array.indexOf(value). Use it inside aggregation expression stages like $project and $addFields, not as a standalone query filter operator.
Foundation
📝 Syntax
The $indexOfArray operator takes an array expression, a search value, and optional range bounds:
// ["placed", "paid", "pending", "shipped"]
// → pendingAfterStep2: 2
// ["placed", "pending", "paid", "shipped"]
// → pendingAfterStep2: -1 (index 1 is skipped because start is 2)
How It Works
The third argument (start) tells MongoDB to ignore elements before that index. This is helpful when you only care about occurrences after a certain step in a timeline or workflow.
Example 3 — Check Whether a Value Exists
Convert the index into a boolean hasFeaturedTag field:
// tags includes "featured" → hasFeaturedTag: true
// tags without "featured" → hasFeaturedTag: false
How It Works
When the index is -1, $gte returns false. When the value is found (index 0 or higher), the result is true. For simple membership tests in aggregation, query $in filters documents; this pattern adds a boolean field per document.
Example 4 — $indexOfArray Inside $cond
Label articles based on whether "mongodb" appears in their tags:
If $indexOfArray finds "mongodb", the index is >= 0 and $cond outputs "database". Otherwise the article is labeled "general". Pair this with $arrayElemAt when you need the element at the found index.
Bonus — Combine with $arrayElemAt
After finding an index, retrieve the neighboring element:
First compute the index of "mongodb", then use $arrayElemAt with index + 1 to get the next tag. If "mongodb" is last or missing, $arrayElemAt returns null.
Applications
🚀 Use Cases
Tag and category lookup — find where a label appears in a document’s tag array.
Workflow timelines — locate the first "pending" or "approved" step in a status history.
Existence checks in aggregation — convert index >= 0 into boolean flags for reporting.
Array navigation — combine with $arrayElemAt to read elements before or after a found position.
🧠 How $indexOfArray Works
1
MongoDB reads the array and search value
The pipeline evaluates the array (e.g. "$tags") and the value to find (e.g. "mongodb").
Input
2
$indexOfArray scans the range
MongoDB walks from start to end, comparing each element to the search value until a match is found.
Search
3
The index is stored in the pipeline
A zero-based index is written to your output field, or -1 if no match exists in the range.
Output
=
📊
Precise array positions
You get index data ready for boolean checks, conditional labels, and paired array lookups.
Wrap Up
Conclusion
The $indexOfArray operator is a focused but powerful tool for working with arrays in MongoDB aggregation pipelines. It tells you where a value lives inside an array — not just whether it exists — which unlocks navigation, categorization, and timeline analysis patterns.
For beginners, the key idea is simple: wrap your array and search value in { $indexOfArray: [ ... ] } inside a stage like $project. A result of -1 means “not found”; any index 0 or higher means the value was located.
Check for -1 before using the index with $arrayElemAt
Use $gte: [ { $indexOfArray: ... }, 0 ] for existence booleans
Pass start and end when you only need a partial search
Remember indexes are zero-based (first element is 0)
Pair with $cond for category or status labeling
❌ Don’t
Use $indexOfArray as a query filter outside expressions
Confuse it with query operator $in (different purpose)
Assume it finds all occurrences (only the first match is returned)
Forget that missing values return -1, not null
Use it on strings directly — use $indexOfBytes or $indexOfCP for strings
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $indexOfArray
Use these points when locating values inside arrays.
5
Core concepts
🔢01
Array Index
Finds position in array.
Purpose
📝02
Four Arguments
array, search, start, end.
Syntax
🛠03
Pipeline Stages
$project, $addFields, $cond.
Usage
🔍04
Not Found
Returns -1.
Edge case
📦05
Pair Operators
$arrayElemAt, $cond.
Pattern
❓ Frequently Asked Questions
$indexOfArray returns the zero-based index of the first occurrence of a search value inside an array. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $indexOfArray: [ <array>, <search>, <start>, <end> ] }. The start and end arguments are optional and limit the search range within the array.
It returns -1 when the search value is not present in the array (within the optional start/end range). This matches JavaScript Array.indexOf() behavior.
$in is a query operator that filters documents when a field matches any value in a list. $indexOfArray is an aggregation expression that returns the numeric position of a value inside an array field.
Yes. start is the index to begin searching (default 0). end is the index before which searching stops (default array length). This lets you search only part of an array.