You can use $indexOfArray operator for this. Let us create a collection with documents −
>db.getIndexDemo.insertOne({"InstructorName":"Chris","InstructorSubject":["MongoDB","MySQL","Java","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cbd5251de8cc557214c0df8") }
Display all documents from a collection with the help of find() method −
> db.getIndexDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbd5251de8cc557214c0df8"), "InstructorName" : "Chris", "InstructorSubject" : [ "MongoDB", "MySQL", "Java", "C++" ] }
Following is the query to get index of given element in an array field in MongoDB −
> db.getIndexDemo.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$InstructorSubject", "MongoDB" ] } } } ] );
This will produce the following output −
{ "_id" : ObjectId("5cbd5251de8cc557214c0df8"), "matchedIndex" : 0 }
Following is the query to get index of another element in array field in MongoDB −
> db.getIndexDemo.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$InstructorSubject", "C++" ] } } } ] );
This will produce the following output −
{ "_id" : ObjectId("5cbd5251de8cc557214c0df8"), "matchedIndex" : 3 }
NOTE - As we know, in most of the languages array index starts from 0, the first element of the array will have 0 index and last element will have (n-1) index, where n is the number of elements of the array.