Introduction to MongoDB $switch Operator

The $switch operator is one of the conditional statement operators in MongoDB, which can execute multiple different operations based on the given expression value, similar to the switch statement in programming languages. The $switch operator can dynamically generate different results based on conditions.

Syntax

The syntax of the $switch operator is as follows:

{
  $switch: {
    branches: [
      {
        case: <expression>,
        then: <expression>
      },
      {
        case: <expression>,
        then: <expression>
      },
      ...
    ],
    default: <expression>
  }
}
  • branches: An array containing multiple branches, each branch includes two fields, case and then.
    • case: An expression used to determine whether the condition of this branch is satisfied.
    • then: An expression used to specify the operation to be executed when the condition of this branch is satisfied.
  • default: An expression used to specify the operation to be executed when no branch meets the condition.

Use Cases

The $switch operator is usually used in scenarios where results need to be dynamically generated based on different conditions. For example:

  • Classify documents based on different conditions.
  • Return different results based on field values in documents.

Examples

Example 1: Classify documents based on different conditions

Suppose we have a collection called fruits, which contains information about multiple fruits, including fruit names, places of origin, colors, etc. Now, we need to classify fruits based on their colors and put fruits of the same color together.

Suppose the collection fruits has the following documents:

{ "_id": 1, "name": "apple", "color": "red", "origin": "China" }
{ "_id": 2, "name": "banana", "color": "yellow", "origin": "Thailand" }
{ "_id": 3, "name": "grape", "color": "red", "origin": "USA" }
{ "_id": 4, "name": "orange", "color": "orange", "origin": "USA" }
{ "_id": 5, "name": "watermelon", "color": "green", "origin": "USA" }

We can use the $switch operator to put fruits of the same color together, using the following query:

db.fruits.aggregate([
  {
    $project: {
      name: 1,
      color: 1,
      origin: 1,
      fruit_type: {
        $switch: {
          branches: [
            { case: { $eq: ["$color", "red"] }, then: "red_fruit" },
            { case: { $eq: ["$color", "yellow"] }, then: "yellow_fruit" },
            { case: { $eq: ["$color", "orange"] }, then: "orange_fruit" },
            { case: { $eq: ["$color", "green"] }, then: "green_fruit" }
          ],
          default: "unknown"
        }
      }
    }
  }
])

After executing the above query statement, the returned results are as follows:

{ "_id": 1, "name": "apple", "color": "red", "origin": "China", "fruit_type": "red_fruit" }
{ "_id": 2, "name": "banana", "color": "yellow", "origin": "Thailand", "fruit_type": "yellow_fruit" }
{ "_id": 3, "name": "grape", "color": "red", "origin": "USA", "fruit_type": "red_fruit" }
{ "_id": 4, "name": "orange", "color": "orange", "origin": "USA", "fruit_type": "orange_fruit" }
{ "_id": 5, "name": "watermelon", "color": "green", "origin": "USA", "fruit_type": "green_fruit" }

In the above query statement, the branches property of the $switch operator is an array containing multiple case and then sub-properties used to match different conditions. If there is no match, the value of the default property will be returned. In this example, we match the color of the fruit as a case and save the matching result in the fruit_type field.

Example 2: Conditional Calculation Using the $switch Operator

Suppose we have a collection users containing information about multiple users, including their usernames, gender, age, etc. Now we need to classify users by their age and calculate the number of people in different age groups. We can use the $switch operator to achieve this.

Suppose the users collection contains the following documents:

{ "_id": 1, "username": "Tom", "gender": "male", "age": 20 }
{ "_id": 2, "username": "Jane", "gender": "female", "age": 25 }
{ "_id": 3, "username": "John", "gender": "male", "age": 30 }
{ "_id": 4, "username": "Lucy", "gender": "female", "age": 35 }
{ "_id": 5, "username": "Jack", "gender": "male", "age": 40 }

Now, we need to classify users based on their age and calculate the number of people in different age groups, as shown in the following implementation:

db.users.aggregate([
  {
    $project: {
      ageGroup: {
        $switch: {
          branches: [
            {
              case: { $lt: ["$age", 20] },
              then: "Under 20"
            },
            {
              case: { $and: [{ $gte: ["$age", 20] }, { $lt: ["$age", 30] }] },
              then: "20-29"
            },
            {
              case: { $and: [{ $gte: ["$age", 30] }, { $lt: ["$age", 40] }] },
              then: "30-39"
            },
            {
              case: { $gte: ["$age", 40] },
              then: "40 and above"
            }
          ],
          default: "Unknown"
        }
      }
    }
  },
  {
    $group: {
      _id: "$ageGroup",
      count: { $sum: 1 }
    }
  }
])

Explanation:

Firstly, in the $project stage, the document is transformed into the ageGroup field, which is computed using the $switch operator. The $switch operator specifies multiple conditions through the branches array, where each condition is specified by the case property, and the then property specifies the value to be computed for that condition. The default property specifies the default value to be used if none of the conditions are met.

Next, in the $group stage, the ageGroup field is grouped, and the $sum operator is used to calculate the number of documents in each group, resulting in the number of people in different age groups.

When running the code above, the following result is obtained:

{ "_id": "20-29", "count": 2 }
{ "_id": "30-39", "count": 2 }
{ "_id": "40 and above", "count": 1 }

The above results indicate that there are 2 users between the ages of 20 and 29, 2 users between the ages of 30 and 39, and 1 user aged 40 and above.

Conclusion

Through the introduction and example of the $switch operator in this article, we can see the powerful function of the $switch operator in MongoDB. It can perform different operations based on different conditions and achieve complex data classification and calculation, improving the efficiency and accuracy of data processing. At the same time, it is important to pay attention to the correctness of syntax and the rationality of usage scenarios when using the $switch operator to avoid unnecessary errors and performance loss.