Skip to main content

db.command.aggregate.slice

1. Operator Description

Function: Similar to JavaScript's slice method. Returns the specified subset of a given array.

Declaration: db.command.aggregate.slice([array, n])

There are two syntax forms:

Returns n elements from the beginning or the end.

db.command.aggregate.slice([array, n])

Returns n elements forward or backward starting from a specified position (treated as the beginning of the array).

db.command.aggregate.slice([array, position, n])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredDetails of each element in the array are described below.

Array Element Description:

<array> can be any expression that resolves to an array.

<position> can be any expression that resolves to an integer. If positive, the <position>-th element of the array is treated as the start position; if <position> exceeds the array length, slice returns an empty array. If negative, the <position>-th element from the end of the array is treated as the start position; if the absolute value of <position> exceeds the array length, the start position defaults to the beginning of the array.

<n> can be any expression that resolves to an integer. If <position> is provided, <n> must be a positive integer. If positive, slice returns the first n elements. If negative, slice returns the last n elements.

3. Sample Code

Suppose the collection people contains the following records:

{ "_id": 1, "hobbies": [ "basketball", "football", "tennis", "badminton" ] }
{ "_id": 2, "hobbies": [ "golf", "handball" ] }
{ "_id": 3, "hobbies": [ "table tennis", "swimming", "rowing" ] }

Uniformly return the first two hobbies:

// Sample code in the Cloud Function environment
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('fruits')
.aggregate()
.project({
hobbies: $.slice(['$hobbies', 2])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "hobbies": [ "basketball", "football" ] }
{ "_id": 2, "hobbies": [ "golf", "handball" ] }
{ "_id": 3, "hobbies": [ "table tennis", "swimming" ] }