How to compare attributes of different objects in MongoDB object array?

To compare attributes of different objects in a MongoDB object array, use $let along with $indexOfArray to locate specific array elements and compare their values using comparison operators.

Syntax

db.collection.find({
    "$expr": {
        "$let": {
            "vars": {
                "element1": {"$arrayElemAt": ["$arrayName", {"$indexOfArray": ["$arrayName.field", "value1"]}]},
                "element2": {"$arrayElemAt": ["$arrayName", {"$indexOfArray": ["$arrayName.field", "value2"]}]}
            },
            "in": {"$comparisonOperator": ["$$element1.attribute", "$$element2.attribute"]}
        }
    }
});

Sample Data

db.demo366.insertOne({
    "Name": "Chris",
    "details": [
        {
            "Id": "John1",
            "value": "test"
        },
        {
            "Id": "John2",
            "value": 18
        },
        {
            "Id": "John3",
            "value": 20
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e57ddd92ae06a1609a00ae7")
}

Example: Compare Values of John2 and John3

Query to find documents where John2's value is less than John3's value ?

db.demo366.find({
    "$expr": {
        "$let": {
            "vars": {
                "john2": {"$arrayElemAt": ["$details", {"$indexOfArray": ["$details.Id", "John2"]}]},
                "john3": {"$arrayElemAt": ["$details", {"$indexOfArray": ["$details.Id", "John3"]}]}
            },
            "in": {"$lt": ["$$john2.value", "$$john3.value"]}
        }
    }
});
{
    "_id": ObjectId("5e57ddd92ae06a1609a00ae7"),
    "Name": "Chris",
    "details": [
        { "Id": "John1", "value": "test" },
        { "Id": "John2", "value": 18 },
        { "Id": "John3", "value": 20 }
    ]
}

How It Works

  • $indexOfArray finds the index position of elements with specific Id values
  • $arrayElemAt extracts the complete object at that index position
  • $let creates variables to store the extracted objects
  • $lt compares the value attributes (18 < 20 returns true)

Conclusion

Use $let with $indexOfArray and $arrayElemAt to compare attributes between different objects in MongoDB arrays. This approach allows flexible comparisons using any MongoDB comparison operator.

Updated on: 2026-03-15T02:40:06+05:30

736 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements