Aggregate.match
1. Interface Description
Function: Aggregation stage. Filters documents based on conditions and passes those that meet the conditions to the next pipeline stage.
Syntax: match({ <field name>: <expression> })
2. Input Parameters
Parameter | Type | Required | Description |
---|---|---|---|
key | expression | Required | key is any custom field name. Its value expression can directly use native types such as number and string , or use aggregation search operators. |
3. Response
Parameter | Type | Required | Description |
---|---|---|---|
- | Aggregate | Yes | Aggregation object |
4. Sample Code
Suppose the collection articles
contains the following records:
{ "_id" : "1", "author" : "stark", "score" : 80 }
{ "_id" : "2", "author" : "stark", "score" : 85 }
{ "_id" : "3", "author" : "bob", "score" : 60 }
{ "_id" : "4", "author" : "li", "score" : 55 }
{ "_id" : "5", "author" : "jimmy", "score" : 60 }
{ "_id" : "6", "author" : "li", "score" : 94 }
{ "_id" : "7", "author" : "justan", "score" : 95 }
Match
Below is a direct match example:
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("articles")
.aggregate()
.match({
author: "stark",
})
.end();
console.log(res.data);
};
This code attempts to find all articles where the author
field is stark
. The matches are as follows:
{ "_id" : "1", "author" : "stark", "score" : 80 }
{ "_id" : "2", "author" : "stark", "score" : 85 }
Count
After
match` filters out documents, it can also be used in conjunction with other pipeline stages.
For example, in the following example, we use group
in conjunction to calculate the number of documents where the score
field is greater than 80
:
const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "xxx",
});
const db = app.database();
const { gt, sum } = db.command.aggregate;
exports.main = async (event, context) => {
const res = await db
.collection("articles")
.aggregate()
.match({
score: gt(80),
})
.group({
_id: null,
count: sum(1),
})
.end();
console.log(res.data);
};
The return value is as follows:
{ "_id": null, "count": 3 }