Retrieve the position in an Array in MongoDB?

To retrieve the position of an element in an array in MongoDB, you can use the map-reduce approach with JavaScript's indexOf() method. This technique allows you to find the index position of any array element.

Syntax

db.collection.mapReduce(
    function() {
        emit(this._id, { "IndexValue": this.arrayField.indexOf("searchValue") });
    },
    function() {},
    {
        "out": { "inline": 1 },
        "query": { "arrayField": "searchValue" }
    }
);

Sample Data

Let us first create a collection with documents ?

db.retrievePositionDemo.insertOne({
    "Subjects": ["MySQL", "MongoDB", "Java"]
});

Display the document to verify ?

db.retrievePositionDemo.find().pretty();
{
    "_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
    "Subjects" : [
        "MySQL",
        "MongoDB",
        "Java"
    ]
}

Example 1: Find Position of "MongoDB"

db.retrievePositionDemo.mapReduce(
    function() {
        emit(this._id, { "IndexValue": this.Subjects.indexOf("MongoDB") });
    },
    function() {},
    {
        "out": { "inline": 1 },
        "query": { "Subjects": "MongoDB" }
    }
);
{
    "results" : [
        {
            "_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
            "value" : {
                "IndexValue" : 1
            }
        }
    ],
    "timeMillis" : 662,
    "counts" : {
        "input" : 1,
        "emit" : 1,
        "reduce" : 0,
        "output" : 1
    },
    "ok" : 1
}

Example 2: Find Position of "Java"

db.retrievePositionDemo.mapReduce(
    function() {
        emit(this._id, { "IndexValue": this.Subjects.indexOf("Java") });
    },
    function() {},
    {
        "out": { "inline": 1 },
        "query": { "Subjects": "Java" }
    }
);
{
    "results" : [
        {
            "_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
            "value" : {
                "IndexValue" : 2
            }
        }
    ],
    "timeMillis" : 30,
    "counts" : {
        "input" : 1,
        "emit" : 1,
        "reduce" : 0,
        "output" : 1
    },
    "ok" : 1
}

How It Works

  • The map function uses indexOf() to find the element's position in the array
  • Array indexing is zero-based: "MySQL" is at position 0, "MongoDB" at position 1, "Java" at position 2
  • The query parameter filters documents containing the target element
  • Returns -1 if the element is not found in the array

Conclusion

Map-reduce with JavaScript's indexOf() method effectively retrieves array element positions in MongoDB. The IndexValue in the result shows the zero-based position of the searched element within the array.

Updated on: 2026-03-15T00:54:24+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements