Skip to main content

Aggregate.sortByCount

1. Interface Description

Function: Groups the input collection based on the input expression (group). Then calculates the count of distinct groups, sorts these groups by their counts, and returns the sorted results.

Syntax: sortByCount(<expression>)

2. Input Parameters

ParameterTypeRequiredDescription
-AggregateRequiredThe expression is in the form of $ + specified field. Note: Do not omit the $ symbol.

3. Response

ParameterTypeRequiredDescription
-AggregateYesAggregation object

4. Sample Code

Basic Statistical Types

Suppose the collection passages contains the following records:

{ "category": "Web" }
{ "category": "Web" }
{ "category": "Life" }

The following code counts the article categories and calculates the quantity for each category, i.e., performing the sortByCount aggregation operation on the category field.

const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "xxx",
});

const db = app.database();

exports.main = async (event, context) => {
const res = await db
.collection("passages")
.aggregate()
.sortByCount("$category")
.end();
console.log(res.data);
};

The returned results are as follows: There are 2 articles under the Web category and 1 article under the Life category.

{ "_id": "Web", "count": 2 }
{ "_id": "Life", "count": 1 }

Destructuring Array Type

Suppose the collection passages contains the following records: the tags field is of array type.

{ "tags": [ "JavaScript", "C#" ] }
{ "tags": [ "Go", "C#" ] }
{ "tags": [ "Go", "Python", "JavaScript" ] }

How to count the article tags and calculate the quantity for each tag? Since the tags field is an array, use the unwind operator to deconstruct the tags field and then call sortByCount.

The following code implements this functionality:

const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "xxx",
});

const db = app.database();

exports.main = async (event, context) => {
const res = await db
.collection("passages")
.aggregate()
.unwind(`$tags`)
.sortByCount(`$tags`)
.end();
console.log(res.data);
};

The returned result is as follows:

{ "_id": "Go", "count": 2 }
{ "_id": "C#", "count": 2 }
{ "_id": "JavaScript", "count": 2 }
{ "_id": "Python", "count": 1 }