$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()