Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.