Starting with version MongoDB 3.4, we can use the $indexOfArray operator to return the index at which the given element can be found in the array.
$indexOfArray takes three arguments. The first is the name of the array field with the $ prefix.
The second element, and the third optional is the index to start the search. $indexOfArray returns the first index in which the element is found if the index to start the search is not specified.
Demo:
> db.collection.insertOne( { "_id" : 123, "food": [ "apple", "mango", "banana", "mango" ] } ) { "acknowledged" : true, "insertedId" : 123 } > db.collection.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$food", "mango" ] } } } ] ) { "_id" : 123, "matchedIndex" : 1 } > db.collection.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$food", "mango", 2 ] } } } ] ) { "_id" : 123, "matchedIndex" : 3 } > db.collection.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$food", "apricot" ] } } } ] ) { "_id" : 123, "matchedIndex" : -1 }
source share