Supported on: Cloud Function 1.4.0
A query operator for using aggregation expressions within query statements. This method takes one parameter, which must be an aggregation expression.
Parameters
aggregateExpression: Expression
One or more elements to be added to the array
Return Value
Command
Usage Instructions
exprcan be used to introduce aggregation expressions in the aggregationmatchpipeline stage- If the aggregation
matchstage is within alookupstage, theexprexpression can utilize variables defined via theletparameter inlookup. For specific examples, see theSpecify multiple join conditionsexample inlookup exprcan be used in standard query statements (where) to introduce aggregation expressions
Sample Code 1: Comparing Two Fields in the Same Record
Assume the data structure of the items collection is as follows:
{
"_id": string,
"inStock": number, // Stock quantity
"ordered": number // Ordered quantity
}
Retrieve records where the ordered quantity is greater than the stock quantity:
const _ = db.command
const $ = _.aggregate
db.collection('items').where(_.expr($.gt(['$ordered', '$inStock']))).get()
Example Code 2: Use with Conditional Statements
Assume the data structure of the items collection is as follows:
{
"_id": string,
"price": number
}
Assume items with a price less than or equal to 10 receive a 20% discount, and items with a price greater than 10 receive a 50% discount. Query the database to return records where the discounted price is less than or equal to 8:
const _ = db.command
const $ = _.aggregate
db.collection('items').where(_.expr(
$.lt(
$.cond({
if: $.gte('$price', 10),
then: $.multiply(['$price', '0.5']),
else: $.multiply(['$price', '0.8']),
})
,
8
)
).get()