Compare multiple properties in MongoDB?

To compare multiple properties in MongoDB, use the $where operator which allows JavaScript expressions to evaluate conditions between different fields or array elements within the same document.

Syntax

db.collection.find({
    $where: "this.field1 > this.field2"
});

Sample Data

Let us create a collection with sample documents ?

db.comparingMultiplePropertiesDemo.insertOne({
    "Values": [10, 70, 60]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cf228fcb64a577be5a2bc0a")
}

Display the document to verify insertion ?

db.comparingMultiplePropertiesDemo.find().pretty();
{
    "_id": ObjectId("5cf228fcb64a577be5a2bc0a"),
    "Values": [
        10,
        70,
        60
    ]
}

Case 1: True Condition

Compare if the second array element is greater than the third element ?

db.comparingMultiplePropertiesDemo.find({
    $where: "this.Values[1] > this.Values[2]"
});
{
    "_id": ObjectId("5cf228fcb64a577be5a2bc0a"),
    "Values": [10, 70, 60]
}

The document is returned because 70 > 60 is true.

Case 2: False Condition

Compare if the second array element is less than the third element ?

db.comparingMultiplePropertiesDemo.find({
    $where: "this.Values[1] < this.Values[2]"
});

No documents are returned since 70

Key Points

  • Use this to reference the current document being evaluated
  • $where executes JavaScript, so it's slower than regular MongoDB operators
  • Only use $where when other operators cannot achieve the comparison

Conclusion

The $where operator enables JavaScript-based comparisons between multiple properties in MongoDB. Use it sparingly as it's less efficient than native MongoDB operators but powerful for complex field comparisons.

Updated on: 2026-03-15T01:28:40+05:30

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements