Skip to main content

db.command.aggregate.ifNull

1. Operator Description

Function: Evaluates a given expression and returns a replacement value if the expression results in null, undefined, or does not exist; otherwise returns the original value.

Declaration: ifNull([ <expression>, <replacement> ])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredarray of aggregate expressions

3. Sample Code

Suppose the collection items contains the following records:

{ "_id": "0", "name": "A", "description": "This is product A" }
{ "_id": "1", "name": "B", "description": null }
{ "_id": "2", "name": "C" }

We can use ifNull to provide a replacement value for documents that either lack the desc field or have a desc field value of null.

// 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({
_id: 0,
name: 1,
description: $.ifNull(['$description', 'description missing'])
})
.end()
console.log(res.data)
}

The output is as follows:

{ "name": "A", "description": "This is product A" }
{ "name": "B", "description": "description missing" }
{ "name": "C", "description": "description missing" }