Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write switch/case condition in Mongodb $match aggregate

I have a collection named Projects; In this collection, I have a field for project's currency and a field for price amount.

In Express search route, I have 2 variables called USDamount and EURamount. my question is that how I can search for match priced projects by USDamount when document's currency is 'USD' and search by EURamount when document's currency is 'EUR' and so on for other currencies(it means I need a switch/case instead of if/else)?

like image 261
Pouya Jabbarisani Avatar asked Jan 19 '26 11:01

Pouya Jabbarisani


1 Answers

Without detailed information, in Aggregations you can use the switch statement MongoDB documentation and in your queries it look something like this:

db.getCollection("Projects").aggregate(
    [
        { $project:
            {price : 
                {$switch: {
                   branches: [
                      { case: {$eq: ['$currency', 'USD']}, then: '$USDAmount' },
                      { case: {$eq: ['$currency', 'EUR']}, then: '$EURAmount' } ],
                   default: 0
                   }
                }
            }
        }
    ]
)

Note: to produce a compound object including Currency and Amount, you could replace (I.E. '$USDAmount') with:

{'currency': '$currency', 'amount': '$USDAmount' }

Note that I have added a default price of 0; you will probably want to add a $match operator to the pipeline before the $project.

A more complicated example can be found here.

like image 122
Dylan Brams Avatar answered Jan 21 '26 02:01

Dylan Brams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!