MongoDB

How to Use the MongoDB $Cond Operator

The $cond is a ternary operator of MongoDB that accepts an array of three statements, the first of which applies to a Boolean value. If the first statement responds to true, $cond explores and returns the outcomes of the second statement. If the first statement returns false, $cond examines and provides the third statement. It performs the conditional expressions and controls the output based on certain conditions. In this tutorial, the implementation demonstrates more regarding the MongoDB $consd operator.

db.stock.insertMany([

{ _id: 1, item:"Juice", price: 200 , quantity: 3 , status: "In-Stock"},

{ _id: 2, item:"Cookies", price: 250 , quantity: 5 , status: "In-Stock"},

{ _id: 3, item:"Meat", price: 300 , quantity: 5 , status: "Out Of Stock"},

{ _id: 4, item:"Milk", price: 450 , quantity: 10 , status: "In-Stock"},

{ _id: 5, item:"Bread", price: 500 , quantity: 8 , status: "Out Of Stock"}

])

Before delving into the implementation of the $cond operator, we are required to use the MongoDB collection which has some documents inside it. Here, we create the “stock” collection and then call the insertMany() operation on that collection to insert the documents.

Example 1: Using the $cond Operator of MongoDB to Update the Documents

The $cond operator is used as the filter expression to update the document in the collection. The script is demonstrated in the following illustration where the $cond operator is deployed inside the updateMany() method for the document modification.

db.stock.updateMany(
  { },
  [
    {
      $set: {
        Current_status: {
          $cond: {
            if: { $gte: ["$quantity", 5] },
            then: "In Stock",
            else: "Limited"
          }
        }
      }
    }
  ]
)

Here, we apply the updateMany() operation on the “stock” collection. The criteria that is given to the updateMany() method is empty which indicates that it is used on all the documents inside the “stock” collection.

Then, we specify the $set operator in the updateMany() method which sets the defined “Current_Status” field for each document. After that, we employ the $cond operator which evaluates an if-then-else condition and returns the different values based on the results of the $gte operator. The $gte condition is applied to the $quantity field to get a value that is greater than 5.

Next, the “then” statement is provided with the “In Stock” value which is set when the condition of “if” becomes true. Otherwise, the “else” statement is applied to the “Current_Status” field which has the “Out Of Stock” value.

The five documents are matched and updated in the following output:

Now, we examine the updated document using the find() method in the following. It displays the “Current_Status” according to the condition that is specified by the $cond operator.

Example 2: Using the $cond Operator of MongoDB to Aggregate

Next, we use the $cond operator inside the aggregation pipeline to evaluate the conditions and return the results based on that condition. Consider the example of the aggregation pipeline where the $cond operator is deployed.

db.stock.aggregate([
  {
    $project: {
      item: 1,
      price: 1,
      quantity: 1,
      New_Status: {
        $cond: {
          if: { $gt: ["$quantity", 0] },
          then: "In Stock",
          else: "Out of Stock"
        }
      }
    }
  }
])

Here, we initiate the aggregation pipeline on the “stock” collection. Then, we apply the projection inside the aggregation pipeline using the $project operator to specify the fields that we want to include or exclude in the result. To the $project operator, we identify the “name”, “price,” and “quantity” fields with the values set to “1” to be included in the projection.

After that, we set the new field which is “Status” that is defined with the $cond operator to perform the conditional expression. For the condition expression, we use the if-then-else statement which generates the result based on the $quantity field. In the “if” expression, using the comparison operator ($gt), we check whether the value of the $quantity field is greater than 0. If the condition evaluates to true as the quantity is greater than 0, the statement is displayed which is set to “In Stock”.

However, if the $quantity field value is 0 or less than 0, a statement is displayed which is defined with the “Out Of Stock” value.

The documents represent the “status” field in the output which is “In Stock” as the quantity is greater than 0.

Example 3: Using the $cond Operator of MongoDB with the $eq Operator

Moreover, we use the $cond operator where the $eq operator is in the expression to compare the values. Consider the following program where the $cond operator uses the $eq operator:

db.stock.aggregate([
  {
    $project: {
      _id: 1,
      item: 1,
      isAvailable: {
        $cond: { if: { $eq: ["$item", "Cookies"] }, then: "Yes", else: "No" }
      }
    }
  }
]);

Here, we use the aggregation pipeline again on the “stock” collection and use the $project operator for the projection of the fields to be included in the output.

After that, we define the “isAvailable” field which appears in the output where the results of the $cond operator are stored. To the $cond operator, we specify the “if” statement where the $eq operator is called to match the given value that is specified of the $item field. If the value is equal to the “$item” field in the document, “Yes” is placed in the “isAvailable” field. Otherwise, “No” indicates that the value is not matched.

The following output displays the documents with the “Yes” and “No” values according to the $cond operator results:

Example 4: Using the $cond Operator of MongoDB Inside the $group Operator

Lastly, we perform the $cond operator inside the $group stage of the aggregation pipeline to add the alternative values for the specific values. The following is the example where the $cond operator is employed within the $group operator.

db.stock.aggregate(
   [
      {
         $group: {
            _id: "$item",
            Count: { $sum: { $cond: [ { $eq: [ "$status", "Out Of Stock" ] } , 0, 1 ] } }
         }
      }
   ]
)

Here, we use the $group stage aggregation pipeline to group the document based on the specific field and the $cond expression within the $group stage. After that, we set the “_id” of each group to the value of the $item field to the group.

Next, we define the “Count” field for the evaluation based on the $cond operator. We start with the $sum operator which computes the sum of items within each group. Then, we deploy the $cond operator to evaluate the expression where the $eq operator is used to match the value of the $status field.

After that, we set the “0” and “1” for the value to be true and false. If the value is matched, “0” is displayed; otherwise, value “1” is returned.

The documents that are displayed in the output are grouped and evaluated on the status within each group:

Conclusion

We covered MongoDB’s $cond operator which applies the conditional logic to the data. Here, we demonstrated several examples where the $cond operator is used to update the data in the collection and is also called within the aggregation to evaluate the provided expression. Hence, it allows us to perform the complex data transformations based on the data in the collection.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.