Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Wednesday, 21 February 2024

CASE Statement in MongoDB

MongoDB does not have a direct equivalent to SQL's CASE statement. However, you can achieve similar functionality using the $cond operator within an aggregation pipeline. 


Here's an example of how you might use $cond in MongoDB:


Suppose you have a collection named orders with documents containing orderDate field, and you want to categorize orders based on their age:


db.orders.aggregate([

  {

    $project: {

      orderDate: 1,

      orderAge: {

        $cond: {

          if: { $lte: ["$orderDate", new Date()] },

          then: {

            $cond: {

              if: { $gte: [ { $subtract: [new Date(), "$orderDate"] }, 30 * 24 * 60 * 60 * 1000] },

              then: "Recent",

              else: {

                $cond: {

                  if: { $gte: [ { $subtract: [new Date(), "$orderDate"] }, 90 * 24 * 60 * 60 * 1000] },

                  then: "Within 3 Months",

                  else: "More than 3 Months Ago"

                }

              }

            }

          },

          else: null // Handle cases where orderDate is in the future

        }

      }

    }

  }

])


In this example:


- We're using the $project stage to include only the orderDate field and to create a new field orderAge which will contain the result of our categorization.

- Inside the $cond operator, we're checking if the orderDate is less than or equal to the current date.

- If it is, we proceed to further nested $cond operators to categorize orders based on their age in days.

- If the order was placed within the last 30 days, it's categorized as "Recent".

- If the order was placed within the last 90 days but more than 30 days ago, it's categorized as "Within 3 Months".

- If the order was placed more than 90 days ago, it's categorized as "More than 3 Months Ago".


Make sure to adjust the field names (orderDate, etc.) and the date calculations (30 * 24 * 60 * 60 * 1000 for 30 days in milliseconds) based on your specific schema and requirements.


This approach allows you to perform conditional logic within MongoDB's aggregation framework, achieving similar functionality to the CASE statement in SQL databases.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.