Skip to main content

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

FieldTypeRequiredDescription
-<Array>anyRequiredElements at each position are detailed below
FieldTypeRequiredDescription
<array>stringYesAn expression that can be resolved to an array. If resolved to null, indexOfArray returns null
<search>stringYesConditional matching expression applied to each element of the data
<start>integerNoSpecifies the starting index for the search, which must be a non-negative integer
<end>integerNoSpecifies 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 }