定義
構文
$documents ステージの形式は次のとおりです。
{ $documents: <expression> }
制限
$documentsはデータベースレベルの集計パイプラインでのみ使用できます。集計パイプラインの最初のステージとして
$documentsを使用する必要があります。
動作
$documents は、オブジェクトの配列に変換される任意の有効な 式 を受け入れます。 これには以下が含まれます。
現在のドキュメントに解決されない式$myFieldや$$ROOTなど)はエラーになります。
例
パイプライン ステージのテスト
テスト コレクションを作成せずに、パイプライン ステージのテストとデバッグ データを作成します。
db.aggregate( [ { $documents: [ { x: 10 }, { x: 2 }, { x: 5 } ] }, { $bucketAuto: { groupBy: "$x", buckets: 4 } } ] )
集計式ではコレクションを指定しません。 強調表示された$documentsステージの入力データを$bucketAutoステージへの入力として使用します。
[ { _id: { min: 2, max: 5 }, count: 1 }, { _id: { min: 5, max: 10 }, count: 1 }, { _id: { min: 10, max: 10 }, count: 1 } ]
$documents$lookupステージでの ステージの使用
$documentsを使用してコレクション内のドキュメントを他のデータと相関させ、 $lookupの出力を変更します。
locationsコレクションを作成します。
db.locations.insertMany( [ { zip: 94301, name: "Palo Alto" }, { zip: 10019, name: "New York" } ] )
ドキュメントを変換するためのデータソースとして$documentsを使用します。
db.locations.aggregate( [ { $match: {} }, { $lookup: { localField: "zip", foreignField: "zip_id", as: "city_state", pipeline: [ { $documents: [ { zip_id: 94301, name: "Palo Alto, CA" }, { zip_id: 10019, name: "New York, NY" } ] } ] } } ] )
出力は、 locationsコレクション内のデータと$documentsパイプライン ステージ内の値を相関させます。
[ { _id: ObjectId("618949d60f7bfd5f5689490d"), zip: 94301, name: 'Palo Alto', city_state: [ { zip_id: 94301, name: 'Palo Alto, CA' } ] }, { _id: ObjectId("618949d60f7bfd5f5689490e"), zip: 10019, name: 'New York', city_state: [ { zip_id: 10019, name: 'New York, NY' } ] } ]
zipフィールドはzip_idフィールドに対応しますasパラメータは新しい出力フィールドを作成します
MongoDB .NET/ C#ドライバーを使用して$documents ステージを集計パイプラインに追加するには、 オブジェクトでDocuments() PipelineDefinitionメソッドを呼び出します。
次の例では、3 つのドキュメントを作成するパイプラインステージを作成しています。
var documentArray = new[] { new BsonDocument {{ "title", "The Shawshank Redemption" }}, new BsonDocument {{ "title", "Back to the Future" }}, new BsonDocument {{ "title", "Jurassic Park" }}, }; var pipeline = new EmptyPipelineDefinition<NoPipelineInput>() .Documents(documentArray);
MongoDB Node.jsドライバーを使用して $documents ステージを集計パイプラインに追加するには、パイプラインオブジェクトで $documents 演算子を使用します。
次の例では、3 つのドキュメントを作成するパイプラインステージを作成しています。次に、この例では集計パイプラインを実行します。
const pipeline = [ { $documents: [ { "title": "The Shawshank Redemption" }, { "title": "Back to the Future" }, { "title": "Jurassic Park" } ] } ]; const cursor = collection.aggregate(pipeline); return cursor;
詳細
$lookup 構文を使用するサブクエリの詳細については、簡潔なシンタックスを使用した相関サブクエリ を参照してください