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

SDK database Command, aggregate operator, constant operator


May 20, 2021 WeChat Mini Program Development Document


Table of contents


AggregateCommand.literal(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns a literal amount of a value directly without any resolution and processing.

Parameters

value: any

Returns a value

Object

API description

Literal is used as follows:

literal(<>)

If the value is an expression, literal does not parse or evaluate the expression, but instead returns it directly.

The sample code

For example, we have an items collection with the following data:

{ "_id": "0", "price": "$1" }
{ "_id": "1", "price": "$5.60" }
{ "_id": "2", "price": "$8.90" }

Use $literally

The following code uses literal to generate a new field, isOneDollar, to indicate whether the price field is strictly equal to "$1".

Note: We can't use eq here ('$price', '$1') because "$1" is an expression that represents the value of the "1" field, not the literal "$1" of the string.

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    isOneDollar: $.eq(['$price', $.literal('$1')])
  })
  .end()

The output is as follows:

{ "_id": "0", "isOneDollar": true }
{ "_id": "1", "isOneDollar": false }
{ "_id": "2", "isOneDollar": false }

Project a field with a corresponding value of 1

The following code uses literal to project a new field, amount, with a value of 1.

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    price: 1,
    amount: $.literal(1)
  })
  .end()

The output is as follows:

{ "_id": "0", "price": "$1", "amount": 1 }
{ "_id": "1", "price": "$5.60", "amount": 1 }
{ "_id": "2", "price": "$8.90", "amount": 1 }