$indexOfArray - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$indexOfArray

Amazon DocumentDB 中的$indexOfArray运算符用于查找数组中指定元素首次出现的索引。此运算符返回数组中第一个与指定值匹配的元素的从零开始的索引位置。如果未找到该值,则返回 -1。

参数

  • array: 要搜索的数组。

  • value:要在数组中搜索的值。

  • start:(可选)数组中开始搜索的位置。默认值是 0。

示例(MongoDB 外壳)

以下示例演示如何使用 $ indexOfArray 运算符查找每个文档在 “fruits” 数组中首次出现的元素 “mango” 的索引。

创建示例文档

db.collection.insertMany([ { _id: 1, fruits: ["apple", "banana", "cherry", "durian"] }, { _id: 2, fruits: ["mango", "orange", "pineapple"] }, { _id: 3, fruits: ["kiwi", "lemon", "mango"] } ]);

查询示例

db.collection.aggregate([ { $project: { _id: 1, fruitIndex: { $indexOfArray: ["$fruits", "mango"] } } } ]);

输出

{ "_id" : 1, "fruitIndex" : 1 } { "_id" : 2, "fruitIndex" : 0 } { "_id" : 3, "fruitIndex" : 2 }

代码示例

要查看使用该$indexOfArray命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('collection'); const result = await collection.aggregate([ { $project: { _id: 1, fruitIndex: { $indexOfArray: ["$fruits", "mango"] } } } ]).toArray(); console.log(result); client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['collection'] result = list(collection.aggregate([ { '$project': { '_id': 1, 'fruitIndex': { '$indexOfArray': ["$fruits", "mango"] } } } ])) print(result) client.close() example()