db.command.aggregate.literal
1. Operator Description
Functionality: Directly returns the literal value of a given input without any parsing or processing.
Declaration: literal(<value>)
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | any | Required | If <value> is an expression, literal does not parse or evaluate it, but returns the expression directly. |
3. Sample Code
For example, we have a collection items
with the following data:
{ "_id": "0", "price": "$1" }
{ "_id": "1", "price": "$5.60" }
{ "_id": "2", "price": "$8.90" }
Using \$ in Literal Form
The following code uses literal
to generate a new field isOneDollar
, indicating whether the price
field is strictly equal to "$1"
.
Note: We cannot use eq(['$price', '$1'])
here because "$1"
is an expression that represents the value of the "1"
field, rather than the string literal "$1"
.
// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})
const db = app.database()
const $ = db.command.aggregate
const _ = db.command
exports.main = async (event, context) => {
const res = await db
.collection('items')
.aggregate()
.project({
isOneDollar: $.eq(['$price', $.literal('$1')])
})
.end()
console.log(res.data)
}
The output is as follows:
{ "_id": "0", "isOneDollar": true }
{ "_id": "1", "isOneDollar": false }
{ "_id": "2", "isOneDollar": false }
Project a field to the value 1
The following code uses literal
to project a new field amount
with the value 1
.
// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})
const db = app.database()
const $ = db.command.aggregate
const _ = db.command
exports.main = async (event, context) => {
const res = await db
.collection('items')
.aggregate()
.project({
price: 1,
amount: $.literal(1)
})
.end()
console.log(res.data)
}
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 }