

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get index of given element in array field in MongoDB?
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.
- Related Questions & Answers
- Get distinct levels of array field in MongoDB?
- Get a single element from the array of results by index in MongoDB
- Update field in exact element array in MongoDB?
- How to get the index of an array element in older versions on MongoDB?
- MongoDB query on nth element (variable index) of subdocument array
- MongoDB query to get average in aggregation of array element?
- Get count of array elements from a specific field in MongoDB documents?
- Reverse array field in MongoDB?
- Match element in array of MongoDB?
- How to remove an array element by its index in MongoDB?
- Get the duplicate values of a field in MongoDB?
- MongoDB slice array in populated field?
- Delete array element in given index range [L – R] in C++?
- How do you remove an array element by its index in MongoDB
- Creating an index on a nested MongoDB field?
Advertisements