Comparison expressions help you check if values are equal or greater than others inside MongoDB aggregation. This lets you filter or create new data based on conditions.
0
0
Comparison expressions ($eq, $gt in aggregation) in MongoDB
Introduction
When you want to find documents where a field equals a specific value.
When you need to select documents where a number is greater than a certain limit.
When creating new fields that depend on comparing values inside aggregation.
When filtering data in a pipeline to only keep matching documents.
When grouping data and applying conditions to decide what to include.
Syntax
MongoDB
{ $eq: [ <expression1>, <expression2> ] }
{ $gt: [ <expression1>, <expression2> ] }Both $eq and $gt take an array of two expressions to compare.
They return true or false depending on the comparison result.
Examples
Checks if the field
status equals "A".MongoDB
{ $eq: [ "$status", "A" ] }Checks if the field
score is greater than 80.MongoDB
{ $gt: [ "$score", 80 ] }Compares two fields
age and minAge for equality.MongoDB
{ $eq: [ "$age", "$minAge" ] }Sample Program
This aggregation shows each student's name and two new fields: passed is true if their score is greater than 60, and perfectScore is true if their score equals 100.
MongoDB
db.students.aggregate([
{
$project: {
name: 1,
passed: { $gt: [ "$score", 60 ] },
perfectScore: { $eq: [ "$score", 100 ] }
}
}
])OutputSuccess
Important Notes
Remember to use the $ sign before field names inside expressions.
$eq and $gt return boolean values that you can use to filter or create new fields.
These expressions work inside aggregation pipelines, not in simple find queries.
Summary
$eq checks if two values are equal.
$gt checks if the first value is greater than the second.
Use them inside aggregation to compare fields or values and create conditions.