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
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
thisto reference the current document being evaluated -
$whereexecutes JavaScript, so it's slower than regular MongoDB operators - Only use
$wherewhen 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.
