Introduction to MongoDB $cond Operator

The $cond operator in MongoDB is a conditional expression operator used to evaluate and process data.

Syntax

The syntax for the $cond operator is as follows:

{
  $cond: {
     if: <boolean-expression>,
     then: <true-case>,
     else: <false-case>
  }
}

Here, <boolean-expression> is a condition expression used to evaluate the condition, <true-case> is the value returned when the condition is true, and <false-case> is the value returned when the condition is false.

Use cases

The $cond operator is typically used for logical evaluation and processing of data. For example, it can be used to handle exceptional and missing values in data, as well as perform operations like data classification and grouping.

Examples

Example 1: Calculate field value based on condition

Suppose we have a collection products that contains information on multiple products, including product name, price, and whether it is on promotion. We need to calculate the actual price of the products based on whether they are on promotion. If a product is not on promotion, the actual price is the original price; otherwise, the actual price is the promotion price. We can use the $cond operator to perform the calculation:

db.products.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      isPromotion: 1,
      actualPrice: {
        $cond: {
          if: { $eq: ["$isPromotion", true] },
          then: "$promotionPrice",
          else: "$price"
        }
      }
    }
  }
])

In the example above, we use the $project operator to project the data and select the fields to display. The $cond operator is used to calculate the actual price of the products. If a product is on promotion, the promotion price is returned; otherwise, the original price is returned.

Example 2: Classify fields based on condition

Suppose we have a collection students that contains information on multiple students, including their names, ages, and scores. We need to classify the students into three categories based on their scores: excellent, good, and pass. We can use the $cond operator to perform the classification:

db.students.aggregate([
  {
    $project: {
      name: 1,
      age: 1,
      score: 1,
      grade: {
        $cond: {
          if: { $gte: ["$score", 90] },
          then: "Excellent",
          else: {
            $cond: {
              if: { $gte: ["$score", 80] },
              then: "Good",
              else: "Pass"
            }
          }
        }
      }
    }
  }
])

In the example above, we use the $project operator to project the data and select the fields to display. The $cond operator is used to classify the students based on their scores and return the corresponding category.

Conclusion

In MongoDB, the $cond operator is a useful tool for conditional data transformation and processing. By using a conditional expression within $cond, we can create a dynamic field that returns different results based on different condition values. Additionally, $cond can be nested within other stages of the aggregation pipeline to further enhance our data transformation and processing capabilities.

It should be noted that when using $cond, attention must be paid to the return value types of the condition expression and branch expression, otherwise unexpected results may occur. Moreover, because $cond may decrease query performance when dealing with large amounts of data, it should be used with caution in practical applications, and more efficient ways should be used to handle data whenever possible.