$elemMatch - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$elemMatch

Amazon DocumentDB の $elemMatch演算子は、配列フィールドをクエリし、配列内の少なくとも 1 つの要素が指定された条件に一致するドキュメントを返すために使用されます。この演算子は、ネストされた配列または埋め込みドキュメントを持つ複雑なデータ構造がある場合に特に便利です。

プランナーバージョン 2.0 で のインデックスサポートが追加されました$elemMatch

パラメータ

  • field: クエリする配列フィールド。

  • query: 配列要素と照合する基準。

 

$all$elemMatch内での の使用

$all 式内での $elemMatch演算子の使用に関する制限$all 式内での $elemMatch の使用については、「」を参照してください。

例 (MongoDB シェル)

次の例は、 $elemMatch演算子を使用して、parts配列に指定された条件に一致する要素が少なくとも 1 つあるドキュメントを検索する方法を示しています。

サンプルドキュメントを作成する

db.col.insertMany([ { _id: 1, parts: [{ part: "xyz", qty: 10 }, { part: "abc", qty: 20 }] }, { _id: 2, parts: [{ part: "xyz", qty: 5 }, { part: "abc", qty: 10 }] }, { _id: 3, parts: [{ part: "xyz", qty: 15 }, { part: "abc", qty: 100 }] }, { _id: 4, parts: [{ part: "abc", qty: 150 }] } ]);

クエリの例

db.col.find({ parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } } })

出力

{ "_id" : 1, "parts" : [ { "part" : "xyz", "qty" : 10 }, { "part" : "abc", "qty" : 20 } ] } { "_id" : 2, "parts" : [ { "part" : "xyz", "qty" : 5 }, { "part" : "abc", "qty" : 10 } ] }

コードの例

$elemMatch コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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 col = db.collection('col'); const result = await col.find({ parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } } }).toArray(); console.log(JSON.stringify(result, null, 2)); await 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'] col = db['col'] result = list(col.find({ 'parts': { '$elemMatch': {'part': 'xyz', 'qty': {'$lt': 11}} } })) print(result) client.close() example()