Aggregate.sort
1. Interface Description
Function: Aggregation stage. sort Sorts the input documents based on the specified fields.
Declaration: sort({ key1: sortRule1, key2: sortRule2, })
2. Input Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| key | number | Yes | The value specifies the sorting rule, where 1 represents ascending order (from smallest to largest) and -1 represents descending order (from largest to smallest) |
3. Response
| Parameter | Type | Required | Description |
|---|---|---|---|
| - | Aggregate | Yes | Aggregation object |
4. Sample Code
Ascending/Descending Order
Suppose we have a collection articles containing the following data:
{ "_id": "1", "author": "stark", "score": 80, "age": 18 }
{ "_id": "2", "author": "bob", "score": 60, "age": 18 }
{ "_id": "3", "author": "li", "score": 55, "age": 19 }
{ "_id": "4", "author": "jimmy", "score": 60, "age": 22 }
{ "_id": "5", "author": "justan", "score": 95, "age": 33 }
const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "xxx",
});
const db = app.database();
const { gt, sum, concat } = db.command.aggregate;
exports.main = async (event, context) => {
const res = await db
.collection("articles")
.aggregate()
.sort({
age: -1,
score: -1,
})
.end();
console.log(res.data);
};
The above code performs an aggregation search in the students collection and sorts the results, first by the age field in descending order, then by the score field in descending order.
The output is as follows:
{ "_id": "5", "author": "justan", "score": 95, "age": 33 }
{ "_id": "4", "author": "jimmy", "score": 60, "age": 22 }
{ "_id": "3", "author": "li", "score": 55, "age": 19 }
{ "_id": "1", "author": "stark", "score": 80, "age": 18 }
{ "_id": "2", "author": "bob", "score": 60, "age": 18 }