Skip to main content

db.command.aggregate.filter

1. Operator Description

Function: Returns a subset of the array that meets the given conditions.

Declaration: db.command.aggregate.filter({ input: array, as: string, cond: expression })

2. Operator Parameters

FieldTypeRequiredDescription
inputExpressionRequiredAn expression that resolves to an array.
asstringNoOptional. The variable representing each element in the array, defaults to this.
condExpressionRequiredAn expression that resolves to a boolean value, used to determine whether each element meets the condition. The element name is defined by the as parameter (parameter names must be prefixed with $$, e.g., $$this).

3. Sample Code

Suppose the collection fruits contains the following records:

{
"_id": 1,
"stock": [
{ "name": "apple", "price": 10 },
{ "name": "orange", "price": 20 }
],
}
{
"_id": 2,
"stock": [
{ "name": "lemon", "price": 15 },
],
}
// 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('fruits')
.aggregate()
.project({
stock: $.filter({
input: '$stock',
as: 'item',
cond: $.gte(['$$item.price', 15])
})
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "stock": [ { "name": "orange", "price": 20} ] }
{ "_id": 2, "stock": [ { "name": "lemon", "price": 15 } ] }