Aggregate.sample
1. Interface Description
Function: Aggregation stage. Randomly selects a specified number of records from the documents.
Declaration: sample({ size: <positive integer> })
2. Input Parameters
Parameter | Type | Required | Description |
---|---|---|---|
size | number | Yes | size must be a positive integer, otherwise an error will occur. |
3. Response
Parameter | Type | Required | Description |
---|---|---|---|
- | Aggregate | Yes | Aggregation object |
4. Sample Code
Suppose the document users
contains the following records:
{ "name": "a" }
{ "name": "b" }
Sample Randomly
If a lottery is being conducted now and a lucky user needs to be selected, the sample
method would be called as follows:
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("users")
.aggregate()
.sample({
size: 1,
})
.end();
console.log(res.data);
};
The record of a randomly selected user is returned as follows:
{ "_id": "696529e4-7e82-4e7f-812e-5144714edff6", "name": "b" }