Created
August 16, 2019 13:39
-
-
Save ezirmusitua/5214b3b3539761e822a34dc89cbc9029 to your computer and use it in GitHub Desktop.
[MongoDB Query: `$expr` operator] Mongodb query operator `$expr` usage #mongodb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://docs.mongodb.com/manual/reference/operator/query/expr/#op._S_expr | |
//// $expr can build query expressions that compare fields from the same document in a $match stage. | |
////// Compare Two Fields from A Single Document | |
////// The following operation uses $expr to find documents where the spent amount exceeds the budget | |
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } ) | |
////// Using $expr With Conditional Statements | |
////// The following operation uses $expr with $cond to mimic a conditional statement. It finds documents where the price is less than 5 after the applied discounts. | |
db.supplies.find( { | |
$expr: { | |
$lt:[ { | |
$cond: { | |
if: { $gte: ["$qty", 100] }, | |
then: { $divide: ["$price", 2] }, | |
else: { $divide: ["$price", 4] } | |
} | |
}, | |
5 ] } | |
} ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment