How to get the index of an array element in older versions on MongoDB?


To get index of an array element, use $indexOfArray. Let us create a collection with documents −

> db.demo65.insertOne({"ListOfValues":[10,20,30]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28990ecfb11e5c34d89938")
}
> db.demo65.insertOne({"ListOfValues":[50,60,70,100]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28991ecfb11e5c34d89939")
}
> db.demo65.insertOne({"ListOfValues":[30,40,89,91,98]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28992bcfb11e5c34d8993a")
}

Display all documents from a collection with the help of find() method −

> db.demo65.find();

This will produce the following output −

{ "_id" : ObjectId("5e28990ecfb11e5c34d89938"), "ListOfValues" : [ 10, 20, 30 ] }
{ "_id" : ObjectId("5e28991ecfb11e5c34d89939"), "ListOfValues" : [ 50, 60, 70, 100 ] }
{ "_id" : ObjectId("5e28992bcfb11e5c34d8993a"), "ListOfValues" : [ 30, 40, 89, 91, 98 ] }

Here is the query to get the index of an array element in older versions on MongoDB −

> db.demo65.aggregate(
...    [
...       {
...          $project:
...          {
...             IndexOfAnArrayElement: { $indexOfArray: [ "$ListOfValues", 30] },
...          }
...       }
...    ]
... );

This will produce the following output −

{ "_id" : ObjectId("5e28990ecfb11e5c34d89938"), "IndexOfAnArrayElement" : 2 }
{ "_id" : ObjectId("5e28991ecfb11e5c34d89939"), "IndexOfAnArrayElement" : -1 }
{ "_id" : ObjectId("5e28992bcfb11e5c34d8993a"), "IndexOfAnArrayElement" : 0 }

Updated on: 30-Mar-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements