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
Set gt condition in MongoDB and
The $and operator performs a logical AND operation on an array of one or more expressions. You can combine the $gt condition with other criteria using $and to create complex queries that match documents satisfying multiple conditions.
Syntax
db.collection.find({
$and: [
{ field: { $gt: value } },
{ field: anotherCondition }
]
});
Sample Data
db.demo680.insertMany([
{ Values: 40 },
{ Values: 70 },
{ Values: [80, 30] },
{ Values: 20 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea4461b04263e90dac943fe"),
ObjectId("5ea4461e04263e90dac943ff"),
ObjectId("5ea4462a04263e90dac94400"),
ObjectId("5ea4463304263e90dac94401")
]
}
Display all documents from the collection ?
db.demo680.find();
{ "_id": ObjectId("5ea4461b04263e90dac943fe"), "Values": 40 }
{ "_id": ObjectId("5ea4461e04263e90dac943ff"), "Values": 70 }
{ "_id": ObjectId("5ea4462a04263e90dac94400"), "Values": [80, 30] }
{ "_id": ObjectId("5ea4463304263e90dac94401"), "Values": 20 }
Example: Using $gt with $and
Find documents where Values is greater than 60 AND also contains the value 30 ?
db.demo680.find({
$and: [
{ Values: { $gt: 60 } },
{ Values: 30 }
]
});
{ "_id": ObjectId("5ea4462a04263e90dac94400"), "Values": [80, 30] }
How It Works
The query matches the document with Values: [80, 30] because:
- The array contains 80, which satisfies
{ $gt: 60 } - The array also contains the exact value 30
- Both conditions in the
$andarray are true
Conclusion
Use $and with $gt to create compound queries that require multiple conditions to be satisfied simultaneously. This is particularly useful when working with arrays or combining different comparison operators.
Advertisements
