How to search an array for values present in another array and output the indexes of values found into a new array in MongoDB?

To search an array for values present in another array and output the indexes of values found into a new array in MongoDB, use the $indexOfArray operator combined with $map within an aggregation pipeline.

Syntax

db.collection.aggregate([
    {
        "$project": {
            "Result": {
                "$map": {
                    "input": [searchValues],
                    "in": { "$indexOfArray": ["$arrayField", "$$this"] }
                }
            }
        }
    }
])

Sample Data

db.demo381.insertMany([
    { "Values": [10, 40, 60, 30, 60] },
    { "Values": [100, 500, 700, 500, 800] },
    { "Values": [20, 40, 30, 10, 60] }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("5e5b59f72ae06a1609a00b15"),
        "1": ObjectId("5e5b59f72ae06a1609a00b16"),
        "2": ObjectId("5e5b59f72ae06a1609a00b17")
    }
}

Display all documents from the collection ?

db.demo381.find();
{ "_id": ObjectId("5e5b59f72ae06a1609a00b15"), "Values": [10, 40, 60, 30, 60] }
{ "_id": ObjectId("5e5b59f72ae06a1609a00b16"), "Values": [100, 500, 700, 500, 800] }
{ "_id": ObjectId("5e5b59f72ae06a1609a00b17"), "Values": [20, 40, 30, 10, 60] }

Example

Search for values [10, 40] in each document's Values array and return their indexes ?

db.demo381.aggregate([
    {
        "$project": {
            "Result": {
                "$map": {
                    "input": [10, 40],
                    "in": { "$indexOfArray": ["$Values", "$$this"] }
                }
            }
        }
    }
])
{ "_id": ObjectId("5e5b59f72ae06a1609a00b15"), "Result": [0, 1] }
{ "_id": ObjectId("5e5b59f72ae06a1609a00b16"), "Result": [-1, -1] }
{ "_id": ObjectId("5e5b59f72ae06a1609a00b17"), "Result": [3, 1] }

How It Works

  • $map iterates through the search array [10, 40]
  • $indexOfArray finds the index of each value in the Values array
  • Returns -1 if the value is not found
  • For document 1: 10 is at index 0, 40 is at index 1
  • For document 2: Neither 10 nor 40 exist, so both return -1
  • For document 3: 10 is at index 3, 40 is at index 1

Conclusion

The combination of $map and $indexOfArray allows you to efficiently search for multiple values in an array and return their corresponding indexes. Values not found return -1.

Updated on: 2026-03-15T02:45:02+05:30

678 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements