Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SDK database Command query expression operator


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Command.expr(aggregateExpression: Expression): Command

Support side: Cloud function 1.4.0

A query operator that uses an aggregate expression in a query statement, and the method receives an argument that must be an aggregate expression

Parameters

aggregateExpression: Expression

One or more elements to add to the array

Returns a value

Command

Instructions for use

  1. expr can be used to introduce aggregation expressions in the aggregate match pipeline phase
  2. If the aggregate match stage is within the lookup stage, the variable defined using the let parameter can be used within the lookup expression, as can be seen in the example of the specified multiple connection conditions for lookup
  3. expr can be used to introduce aggregate expressions in a normal query statement (where).

Example code 1: Compare two fields in the same record

Suppose the data structure of the items collection is as follows:

{
  "_id": string,
  "inStock": number, // 库存量
  "ordered": number  // 被订量
}

Find records that are ordered larger than inventory:

const _ = db.command
const $ = _.aggregate
db.collection('items').where(_.expr($.gt('$ordered', '$inStock'))).get()

Example code 2: Used in combination with conditional statements

Suppose the data structure of the items collection is as follows:

{
  "_id": string,
  "price": number
}

Suppose you add an 8 percent discount of less than 10 and a 5 percent discount of 10 or more, and let the database query return a record with a discounted price of less than 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()