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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With