May 20, 2021 WeChat Mini Program Development Document
4. Example code 1: Compare two fields in the same record
5. Example code 2: Used in combination with conditional statements
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
One or more elements to add to the array
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()
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()