Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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: 1matches double type,$type: 2matches string type - When
v1 === v2is true,$type: 2matches 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.
Advertisements
