db.command.aggregate.indexOfArray
1. Operator Description
Function: Finds the index of the first element in an array that equals the given value. If not found, returns -1.
Declaration: db.command.aggregate.indexOfArray([ <array expression>, <search expression>, <start>, <end> ])
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array>any | Required | Elements at each position are detailed below |
Field | Type | Required | Description |
---|---|---|---|
<array> | string | Yes | An expression that can be resolved to an array. If resolved to null, indexOfArray returns null |
<search> | string | Yes | Conditional matching expression applied to each element of the data |
<start> | integer | No | Specifies the starting index for the search, which must be a non-negative integer |
<end> | integer | No | Specifies the ending index for the search, which must be a non-negative integer. If <end> is specified, <start> must also be specified; otherwise, <end> is treated as <start> by default. |
3. Sample Code
Suppose the collection stats
contains the following records:
{
"_id": 1,
"sales": [ 1, 6, 2, 2, 5 ]
}
{
"_id": 2,
"sales": [ 4, 2, 1, 5, 2 ]
}
{
"_id": 3,
"sales": [ 2, 5, 3, 3, 1 ]
}
// 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('stats')
.aggregate()
.project({
index: $.indexOfArray(['$sales', 2, 2])
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "index": 2 }
{ "_id": 2, "index": 4 }
{ "_id": 3, "index": -1 }