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

SDK database Command-aggregate operator-variable operator


May 20, 2021 WeChat Mini Program Development Document


Table of contents


AggregateCommand.let(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Custom variables, and used in the specified expression, return the result of the expression.

Parameters

value: any

Returns a value

Object

API description

Let's syntax is as follows:

db.command.aggregate.let({
  vars: {
    <变量1>: <变量表达式>,
    <变量2>: <变量表达式>,
    ...
  },
  in: <结果表达式>
})

You can define multiple variables in vars, the value of which is evaluated by the variable expression, and the defined variable is accessible only by the resulting expression in in.

When accessing a custom variable in the resulting expression of in, add a double dollar sign ($$) to the name of the variable and enclose it in quotation marks.

The sample code

Suppose the record of a collection of goods that represents an item is as follows: price represents the price of the goods, discount represents the discount rate of the goods, and cost represents the cost of the goods

{ "cost": -10, "discount": 0.95, "price": 100 }
{ "cost": -15, "discount": 0.98, "price": 1 }
{ "cost": -10, "discount": 1, "price": 10 }

Let allows you to define and calculate the actual sales price for each item and assign it to the custom variable priceTotal. Finally, priceTotal and cost are taken and (sum) operations are performed to make a profit on each item.

The code is as follows:

const $ = db.command.aggregate
db
  .collection('goods')
  .aggregate()
  .project({
    profit: $.let({
      vars: {
        priceTotal: $.multiply(['$price', '$discount'])
      },
      in: $.sum(['$$priceTotal', '$cost'])
    })
  })
  .end()

The results of the data returned are as follows:

{ "profit": 85 }
{ "profit": -14.02 }
{ "profit": 0 }