Skip to main content

Aggregate.limit

1. Interface Description

Function: Aggregation stage. Limits the number of records output to the next stage.

Declaration: limit(number)

2. Input Parameters

ParameterTypeRequiredDescription
-numberYesPositive integer

3. Response

ParameterTypeRequiredDescription
-AggregateYesAggregation object

4. Sample Code

Suppose the collection items contains the following records:

{
_id: "1",
price: 10
}
{
_id: "2",
price: 50
}
{
_id: "3",
price: 20
}
{
_id: "4",
price: 80
}
{
_id: "5",
price: 200
}

Return the two smallest records with price greater than 20.

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()
.match({
price: _.gt(20),
})
.sort({
price: 1,
})
.limit(2)
.end();
console.log(res.data);
};

The returned result is as follows:

{
"_id": "3",
"price": 20
}
{
"_id": "4",
"price": 80
}