How do you test if two external values are equal in a MongoDB criteria object?

To test if two external values are equal in a MongoDB criteria object, you can use the $type operator combined with a JavaScript expression that evaluates the equality condition and returns different BSON type numbers.

Syntax

db.collection.find({
    field: "value",
    field: { $type: baseNumber + (value1 === value2) }
});

Sample Data

db.demo211.insertMany([
    { id: 101, "Name": "Chris" },
    { id: 102, "Name": null }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3e298203d395bdc21346fa"),
        ObjectId("5e3e2a5403d395bdc21346fb")
    ]
}
db.demo211.find();
{ "_id": ObjectId("5e3e298203d395bdc21346fa"), "id": 101, "Name": "Chris" }
{ "_id": ObjectId("5e3e2a5403d395bdc21346fb"), "id": 102, "Name": null }

Example: Testing External Value Equality

v1 = 200;
v2 = 200;
db.demo211.find({
    Name: 'Chris',
    Name: { $type: 1 + (v1 === v2) }
});
{ "_id": ObjectId("5e3e298203d395bdc21346fa"), "id": 101, "Name": "Chris" }

How It Works

  • The expression (v1 === v2) returns 1 if values are equal, 0 if different
  • $type: 1 matches double type, $type: 2 matches string type
  • When v1 === v2 is true, $type: 2 matches string values like "Chris"
  • This creates a conditional query based on external variable comparison

Conclusion

Use $type with JavaScript expressions to conditionally filter documents based on external value equality. The boolean result modifies the BSON type number, creating dynamic query conditions.

Updated on: 2026-03-15T01:45:03+05:30

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements