$indexOfArray (Find Element Index in Array)
Last updated: 2026-10-09
$indexOfArray (Find Element Index in Array)
$indexOfArray returns the index of the first occurrence of a value in an array, or -1 when it is absent. Typical uses include checking whether a tag exists and locating a specific element to read it with $arrayElemAt. Optional arguments restrict the search to a start/end index range. It is the array counterpart of $indexOfBytes/$indexOfCP, which operate on strings. Matching uses strict equality, so objects must match as a whole.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $indexOfArray: [ <array>, <searchValue>, <start>, <end> ] }
⚙️ Parameters
| array | The array to search. |
|---|---|
| search value | The value to find. |
| start index | Optional start index, inclusive; defaults to 0. |
| end index | Optional end index, exclusive. |
Returns:The index of the first match, or -1 when not found
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $indexOfArray: locate the 'urgent' tag
db.tasks.aggregate([
{ $project: {
urgentPos: { $indexOfArray: ['$tags', 'urgent'] }
} }
])
Output:
{ '_id': 1, 'urgentPos': 2 }
{ '_id': 2, 'urgentPos': -1 }
📌 Notes
- Only the first match is returned; later duplicates are ignored
- The range is left-closed, right-open: start is inclusive, end is exclusive
- Not found yields -1, which can drive existence checks
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat does $indexOfArray return when the element is missing?
AIt returns -1; check with $ne to test existence.
QCan I restrict the search range?
AYes — the third and fourth arguments are the start (inclusive) and end (exclusive) indexes.
QHow do I search for an object element?
APass the whole object for strict equality, e.g. { $indexOfArray: ['$arr', { a: 1 }] }.