View a markdown version of this page

$lookup - Amazon DocumentDB

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

$lookup

Amazon DocumentDB の$lookup集約ステージでは、2 つのコレクション間で左外部結合を実行できます。このオペレーションでは、一致するフィールド値に基づいて複数のコレクションのデータを組み合わせることができます。これは、関連するコレクションのデータをクエリ結果に組み込む必要がある場合に特に便利です。

パラメータ

  • from: 結合を実行するコレクションの名前。

  • localField: と照合する入力ドキュメントのフィールドforeignField。

  • foreignField: と照合するfromコレクション内のドキュメントのフィールドlocalField。

  • as: fromコレクションから一致するドキュメントを含む出力ドキュメントに追加する新しいフィールドの名前。

  • pipeline: localFieldと が指定されている場合はオプションforeignFieldです。from コレクションで実行する集約パイプライン。パイプラインはfromコレクションからドキュメントを返します。すべてのドキュメントを返すには、空のパイプライン を指定します[]。パイプラインに $outまたは $mergeステージを含めることはできません。「結合条件と相関サブクエリ (MongoDB シェル)」を参照してください。

  • let: オプション。pipeline ステージで使用する変数を定義するドキュメント。変数式を使用して、 に結合されている入力ドキュメントのフィールドにアクセスしますpipeline。パイプラインステージで変数を参照するには、 "$$<variable>"構文を使用します。「結合条件と相関サブクエリ (MongoDB シェル)」を参照してください。

例 (MongoDB シェル)

次の例は、ordersコレクションからcustomersコレクションにデータを結合するシンプルな$lookupオペレーションを示しています。

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

db.customers.insertMany([ { _id: 1, name: "Alice" }, { _id: 2, name: "Bob" }, { _id: 3, name: "Charlie" } ]); db.orders.insertMany([ { _id: 1, customer_id: 1, total: 50 }, { _id: 2, customer_id: 1, total: 100 }, { _id: 3, customer_id: 2, total: 75 } ]);

クエリの例

db.customers.aggregate([ { $lookup: { from: "orders", localField: "_id", foreignField: "customer_id", as: "orders" } } ]);

出力

[ { _id: 1, name: 'Alice', orders: [ { _id: 2, customer_id: 1, total: 100 }, { _id: 1, customer_id: 1, total: 50 } ] }, { _id: 3, name: 'Charlie', orders: [] }, { _id: 2, name: 'Bob', orders: [ { _id: 3, customer_id: 2, total: 75 } ] } ]

結合条件と相関サブクエリ (MongoDB シェル)

バージョン 8.0.2 の新機能。

Amazon DocumentDB $lookupでは、単一の等価一致に加えて、結合されたコレクションで集約パイプラインを実行できます。これは、すべての入力ドキュメントに対して同じサブクエリを実行する相関関係のないサブクエリと、各入力ドキュメントのフィールドから定義された変数を使用してそのドキュメントに相関する結果を返す相関関係のないサブクエリをサポートします。

[Syntax] (構文)

相関サブクエリを実行するには、入力ドキュメントのフィールドの変数を で定義しlet、pipelineステージで参照します。

{ $lookup: { from: <collection to join>, let: { <var_1>: <expression>, ..., <var_n>: <expression> }, pipeline: [ <pipeline to run on the joined collection> ], as: <output array field> } }

パラメータ

  • let: 入力ドキュメントのフィールドから変数を定義するドキュメント。パイプラインステージで変数を参照するには、 "$$<variable>"構文を使用します。変数には、 にネストされた追加のステージを含めpipeline、 の$lookupステージからアクセスできますpipeline。$match ステージでは、変数にアクセスするために $expr演算子を使用する必要があります。相関しないサブクエリの実行を省略letします。

  • pipeline: fromコレクションで実行する集約パイプライン。パイプラインは入力ドキュメントのフィールドに直接アクセスできません。代わりに を使用して変数を定義letし、変数を参照します。すべてのドキュメントを返すには、空のパイプライン を指定します[]。

$match ステージ内の$expr演算子に配置された $eq、、$gt$gte、$lt、および $lte 比較演算子は、結合されたfromコレクションのフィールドをlet変数または定数と比較するときに、コレクションでインデックスを使用できます。

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

db.customers.insertMany([ { _id: 1, name: "Alice", min_total: 60 }, { _id: 2, name: "Bob", min_total: 50 }, { _id: 3, name: "Charlie", min_total: 20 } ]); db.orders.insertMany([ { _id: 1, customer_id: 1, total: 50 }, { _id: 2, customer_id: 1, total: 100 }, { _id: 3, customer_id: 2, total: 75 } ]);

クエリの例

次の例では、各顧客を注文に参加させ、 がその顧客自身のmin_total値以上totalである注文のみを保持します。結合条件と顧客ごとのフィルターは、どちらも 内のlet変数を参照します$expr。

db.customers.aggregate([ { $lookup: { from: "orders", let: { customer_id: "$_id", min_total: "$min_total" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: [ "$customer_id", "$$customer_id" ] }, { $gte: [ "$total", "$$min_total" ] } ] } } }, { $project: { _id: 0, total: 1 } } ], as: "qualifying_orders" } } ]);

出力

[ { _id: 1, name: 'Alice', min_total: 60, qualifying_orders: [ { total: 100 } ] }, { _id: 2, name: 'Bob', min_total: 50, qualifying_orders: [ { total: 75 } ] }, { _id: 3, name: 'Charlie', min_total: 20, qualifying_orders: [] } ]

顧客ごとに、サブクエリはその顧客の _idおよび min_total値で評価されるため、各ドキュメントは独自の相関結果を受け取ります。

簡潔な構文を使用した相関サブクエリ (MongoDB シェル)

バージョン 8.0.2 の新機能。

Amazon DocumentDB は、簡潔な相関サブクエリ構文もサポートしています。この構文は、 localFieldと での等価一致を foreignFieldと組み合わせますpipeline。簡潔な構文では、$matchステージ内の$expr演算子内で等価一致を表現する要件が削除されます。

[Syntax] (構文)

{ $lookup: { from: <collection to join>, localField: <field from the input documents>, foreignField: <field from the documents of the "from" collection>, let: { <var_1>: <expression>, ..., <var_n>: <expression> }, pipeline: [ <pipeline to run> ], as: <output array field> } }

クエリの例

次の例では、前の相関サブクエリの例と同じ結果を返します。_id と の等価一致customer_idは、$expr条件foreignFieldの代わりに localFieldと で表されます。

db.customers.aggregate([ { $lookup: { from: "orders", localField: "_id", foreignField: "customer_id", let: { min_total: "$min_total" }, pipeline: [ { $match: { $expr: { $gte: [ "$total", "$$min_total" ] } } }, { $project: { _id: 0, total: 1 } } ], as: "qualifying_orders" } } ]);

出力

[ { _id: 1, name: 'Alice', min_total: 60, qualifying_orders: [ { total: 100 } ] }, { _id: 2, name: 'Bob', min_total: 50, qualifying_orders: [ { total: 75 } ] }, { _id: 3, name: 'Charlie', min_total: 20, qualifying_orders: [] } ]

相関サブクエリでサポートされているステージ

$lookup パイプラインが を使用する場合let、次のステージで"$$<variable>"変数を参照できます。

  • $match ( $expr演算子を使用)

  • $project

  • $addFields

  • $set

  • $group

  • $bucket

  • $bucketAuto

  • $sortByCount

  • $lookup (ネスト化済み)

  • $graphLookup

$sort、、、、、、、 などの変数式を評価しないステージは$unset、パイプラインでも使用できますが$skip$limit$count$sample$unwind、変数を参照することはできません。

を使用する$lookupパイプラインでは、、let$facet、、$redact、、$replaceRoot$replaceWith$geoNear、$setWindowFields$fill、 $matchの各ステージはサポートされていません$text。

制限事項

  • には $outまたは $mergeステージを含めるpipelineことはできません。

コードの例

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

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'); await client.connect(); const db = client.db('test'); const result = await db.collection('customers').aggregate([ { $lookup: { from: 'orders', localField: '_id', foreignField: 'customer_id', as: 'orders' } } ]).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 collection = db.customers pipeline = [ { "$lookup": { "from": "orders", "localField": "_id", "foreignField": "customer_id", "as": "orders" } } ] result = collection.aggregate(pipeline) for doc in result: print(doc) client.close() example()

関連するサブクエリコードの例

相関サブクエリ ( letと を使用pipeline) で$lookupステージを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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 customers = db.collection('customers'); await customers.insertMany([ { _id: 1, name: "Alice", min_total: 60 }, { _id: 2, name: "Bob", min_total: 50 }, { _id: 3, name: "Charlie", min_total: 20 } ]); const orders = db.collection('orders'); await orders.insertMany([ { _id: 1, customer_id: 1, total: 50 }, { _id: 2, customer_id: 1, total: 100 }, { _id: 3, customer_id: 2, total: 75 } ]); // Correlated subquery: filter each customer's orders with a per-customer threshold const result = await customers.aggregate([ { $lookup: { from: 'orders', localField: '_id', foreignField: 'customer_id', let: { min_total: '$min_total' }, pipeline: [ { $match: { $expr: { $gte: [ '$total', '$$min_total' ] } } }, { $project: { _id: 0, total: 1 } } ], as: 'qualifying_orders' } } ]).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 customers = db.customers customers.insert_many([ { "_id": 1, "name": "Alice", "min_total": 60 }, { "_id": 2, "name": "Bob", "min_total": 50 }, { "_id": 3, "name": "Charlie", "min_total": 20 } ]) orders = db.orders orders.insert_many([ { "_id": 1, "customer_id": 1, "total": 50 }, { "_id": 2, "customer_id": 1, "total": 100 }, { "_id": 3, "customer_id": 2, "total": 75 } ]) # Correlated subquery: filter each customer's orders with a per-customer threshold pipeline = [ { "$lookup": { "from": "orders", "localField": "_id", "foreignField": "customer_id", "let": { "min_total": "$min_total" }, "pipeline": [ { "$match": { "$expr": { "$gte": [ "$total", "$$min_total" ] } } }, { "$project": { "_id": 0, "total": 1 } } ], "as": "qualifying_orders" } } ] result = customers.aggregate(pipeline) for doc in result: print(doc) client.close() example()