$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.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $indexOfArray: [ <array>, <searchValue>, <start>, <end> ] }

⚙️ Parameters

arrayThe array to search.
search valueThe value to find.
start indexOptional start index, inclusive; defaults to 0.
end indexOptional 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

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 }] }.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏