MongoDB $cond

In MongoDB, the $cond aggregation pipeline operator evaluates a boolean expression, and returns one of the two specified return expressions, depending on whether the boolean expression is true or false.

The $cond operator accepts two syntaxes: a longhand syntax and a shorthand syntax. Examples of each are below.

Example

Suppose we have a collection called pets with the following document:

{
	"_id" : 1,
	"name" : "Fetch",
	"type" : "Dog",
	"weight" : 20,
	"height" : 30
}

Longhand Syntax

Here’s an example of applying $cond to that document using the longhand syntax:

db.pets.aggregate(
  [
    { $project: { 
        _id: 0,
        isCanine: { 
          $cond: { if: { "$type": "Dog" }, then: "Yes", else: "No" }
          }
      }
    }
  ]
)

Result:

{ "isCanine" : "Yes" }

In this example, we compared the type field to a literal value.

In the following example, we compare two fields within the document.

db.pets.aggregate(
  [
    { $project: { 
        _id: 0,
        bodyType: { 
          $cond: { 
            if: { 
              $gte: [ "$weight", "$height" ] }, 
              then: "Fat", 
              else: "Skinny" 
              }
          }
      }
    }
  ]
)

Result:

{ "bodyType" : "Skinny" }

Shorthand Syntax

The $cond operator also accepts a shorthand syntax that makes your code more concise.

The shorthand basically involves removing the if, then, and else keywords.

When you do this, you need to enclose the expressions in an array.

In this example, we rewrite the first example to use the shorthand syntax:

db.pets.aggregate(
  [
    { $project: { 
        _id: 0,
        isCanine: { 
          $cond: [ { "$type": "Dog" }, "Yes", "No" ]
          }
      }
    }
  ]
)

Result:

{ "isCanine" : "Yes" }

And here’s the second example using shorthand:

db.pets.aggregate(
  [
    { $project: { 
        _id: 0,
        bodyType: { 
          $cond: [
              { $gte: [ "$weight", "$height" ] }, 
              "Fat", 
              "Skinny" 
              ]
          }
      }
    }
  ]
)

Result:

{ "bodyType" : "Skinny" }