Command.expr(aggregateExpression: Expression): Command

View Markdown

Last edited on 2026-04-15

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

  1. expr can be used to introduce aggregation expressions in the aggregation match pipeline stage
  2. If the aggregation match stage is within a lookup stage, the expr expression can utilize variables defined via the let parameter in lookup. For specific examples, see the Specify multiple join conditions example in lookup
  3. expr can 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()