AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

$ プロジェクト (集計ステージ)

$project

リクエストされたフィールドを含むドキュメントをパイプラインの次のステージに渡します。指定するフィールドは、入力ドキュメントの既存フィールドであっても新規に計算されるフィールドであっても構いません。

$project 次のことが可能です。

  • 入力ドキュメントからフィールドを含めます。

  • _id フィールドを非表示にします。

  • 新しいフィールドを追加するか、既存のフィールドの値をリセットします。

  • 入力ドキュメントからフィールドを除外します。

次の環境でホストされる配置には $project を使用できます。

  • MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン

$project の形式は次のとおりです。

{ $project: { <specification(s)> } }

$project の仕様には次の形式があります。

フォーム
説明

<field>: <1 or true>

フィールドを含めるかどうかを指定します。ゼロ以外の整数も true として扱われます。

_id: <0 or false>

_id フィールドで非表示にする項目を指定します。

条件付きでフィールドを除外するには、代わりに REMOVE 変数を使用します。詳細については、「条件付きでのフィールドの除外」を参照してください。

<field>: <expression>

新規フィールドを追加するか、既存フィールドの値をリセットします。

式が $$REMOVE と評価された場合、フィールドは出力から除外されます。詳細については、「条件付きでのフィールドの除外」を参照してください。

<field>: <0 or false>

フィールドの除外を指定します。

条件付きでフィールドを除外するには、代わりに REMOVE 変数を使用します。詳細については、「条件付きでのフィールドの除外」を参照してください。

_id 以外のフィールドの除外を指定する場合、他の $project 指定は 使用できません。この制限は、REMOVE 変数を使用したフィールドの条件付き除外には適用されません。

フィールドを除外するには、$unset ステージを使用することもできます。

  • デフォルトでは、出力ドキュメントには _id フィールドが含まれます。入力ドキュメントの他のフィールドを含めるには、$project で明示的に指定します。

  • 含めるフィールドとしてドキュメントにないものを指定すると、$project はそのフィールドの指定を無視し、ドキュメントにそのフィールドを追加しません。

_id フィールドはデフォルトで出力ドキュメントに含まれます。出力ドキュメントから _id フィールドを除外するには、$project で _id フィールドを明示的に抑制する必要があります。

フィールドを除外すると、他のすべてのフィールドが出力ドキュメントに表示されます。

{ $project: { "<field1>": 0, "<field2>": 0, ... } } // Return all but the specified fields

_id 以外のフィールドを除外する場合、他の $project 指定形式は使用できません。フィールドを除外する場合、含めるフィールドの指定、既存フィールド値のリセット、新規フィールドの追加のいずれの操作もできません。この制限は、REMOVE 変数を使用したフィールドの条件付き除外には適用されません。

フィールドを除外するには、$unsetを使用することもできます。

集計式で変数 REMOVE を使用して、条件付きでフィールドを非表示にできます。使用例については、「条件付きでのフィールドの除外」を参照してください。

注意

MongoDB には、ドキュメントに新しいフィールドを追加するための $addFields も用意されています。

新しいフィールドを追加したり、既存フィールドの値をリセットしたりするには、フィールド名を指定して、その値を式に設定します。式の詳細については、「式」を参照してください。

フィールドをリテラルに解決される式ではなく、数値やブール値のリテラルに設定するには、$literal 演算子を使用します。それ以外の場合、$project はリテラルを、フィールドを含めるまたは除外するためのフラグとして扱います。

新規フィールドを指定し、既存フィールドのフィールドパスに値を設定すると、フィールド名を実質的に変更できます。

$project ステージでは、角括弧 [] を使用して新しい配列フィールドを直接作成できます。ドキュメントに存在しない配列フィールドを指定した場合にこの操作を実行すると、その配列フィールドの値は null に置き換わります。使用例については、「プロジェクトの新しい配列フィールド」を参照してください。

$project ステージでは配列インデックスを使用できません。

埋め込みドキュメント内のフィールドをプロジェクトするか追加/リセットする場合、ドット表記:を使用できます。

"contact.address.country": <1 or 0 or expression>

フィールドを嵌め込むこともできます:

contact: { address: { country: <1 or 0 or expression> } }

フィールドをネストする場合、フィールドを指定するために埋め込みドキュメント内でドット表記を使用することはできません。例、contact: { "address.country": <1 or 0 or expression> } は 無効 です。

埋め込みドキュメントとその埋め込みドキュメント内のフィールドの両方を同じプロジェクションで指定することはできません。

次の $project ステージは、埋め込み contact ドキュメントと contact.address.country フィールドの両方をプロジェクトしようとするため、Path collision エラーで失敗します。

{ $project: { contact: 1, "contact.address.country": 1 } }

親フィールドと埋め込みフィールドの指定順序にかかわらず、エラーが発生します。次の $project は、同じエラーで失敗します。

{ $project: { "contact.address.country": 1, contact: 1 } }

$project ステージを使用する場合、通常このステージをパイプラインの最後のステージにして、クライアントに返すフィールドを指定するために使用します。

$project ステージをパイプラインの開始または中間で使用して、後続のパイプラインステージに渡されるフィールドの数を減らしてもパフォーマンスが改善する可能性はほとんどありません。データベースではこの最適化が自動的に実行されているためです。

MongoDB は、$project ステージが空のドキュメントとして渡される場合、エラーを返します。

例として、次のパイプラインはエラーを返します。

db.myCollection.aggregate( [ { $project: { }} ] )

$project ステージでは配列インデックスを使用できません。

このページの例では、sample_mflix データセット のデータを使用しています。自己管理型 MongoDB 配置にこのデータセットをロードする方法の詳細については、「サンプル データセットのロード」を参照してください。サンプル データベースに何らかの変更を加えた場合は、今ページの例を実行するには、データベースを削除して再作成する必要がある可能性があります。

次の $project ステージでは、_id フィールド、title フィールド、rated フィールドのみが含まれます。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { title: 1, rated: 1 } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), title: 'The Great Train Robbery', rated: 'TV-G' }]

MongoDB には、デフォルトで _id フィールドが含まれています。$project ステージから _id フィールドを除外するには、プロジェクション ドキュメントで _id フィールドを 0 に設定します。

次の $project ステージでは _id フィールドを除外しますが、title フィールドと rated フィールドは含めます。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project : { _id: 0, title : 1, rated : 1 } }, { $limit: 1 }] )
[ { title: 'The Great Train Robbery', rated: 'TV-G' } ]

次の $project ステージでは、rated フィールドが出力から除外されます。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project : { "rated": 0 } }, { $limit: 1 }] )

フィールドを除外するには、$unset ステージを使用します。

次の $project ステージでは、imdb.id フィールドと type フィールドが出力から除外されます。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { "imdb.id": 0, "type": 0 } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), plot: 'A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.', genres: [ 'Short', 'Western' ], runtime: 11, cast: [ 'A.C. Abadie', "Gilbert M. 'Broncho Billy' Anderson", 'George Barnes', 'Justus D. Barnes' ], poster: 'https://m.media-amazon.com/images/M/MV5BMTU3NjE5NzYtYTYyNS00MDVmLWIwYjgtMmYwYWIxZDYyNzU2XkEyXkFqcGdeQXVyNzQzNzQxNzI@._V1_SY1000_SX677_AL_.jpg', title: 'The Great Train Robbery', fullplot: "Among the earliest existing films in American cinema - notable as the first film that presented a narrative story to tell - it depicts a group of cowboy outlaws who hold up a train and rob the passengers. They are then pursued by a Sheriff's posse. Several scenes have color included - all hand tinted.", languages: [ 'English' ], released: ISODate('1903-12-01T00:00:00.000Z'), directors: [ 'Edwin S. Porter' ], rated: 'TV-G', awards: { wins: 1, nominations: 0, text: '1 win.' }, lastupdated: '2015-08-13 00:27:59.177000000', year: 1903, imdb: { rating: 7.4, votes: 9847 }, countries: [ 'USA' ], tomatoes: { viewer: { rating: 3.7, numReviews: 2559, meter: 75 }, fresh: 6, critic: { rating: 7.6, numReviews: 6, meter: 100 }, rotten: 0, lastUpdated: ISODate('2015-08-08T19:16:10.000Z') }, num_mflix_comments: 0 }]

あるいは、除外指定をドキュメント内にネストすることもできます。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { "imdb": { "id": 0 }, "type" : 0 } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), plot: 'A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.', genres: [ 'Short', 'Western' ], runtime: 11, cast: [ 'A.C. Abadie', "Gilbert M. 'Broncho Billy' Anderson", 'George Barnes', 'Justus D. Barnes' ], poster: 'https://m.media-amazon.com/images/M/MV5BMTU3NjE5NzYtYTYyNS00MDVmLWIwYjgtMmYwYWIxZDYyNzU2XkEyXkFqcGdeQXVyNzQzNzQxNzI@._V1_SY1000_SX677_AL_.jpg', title: 'The Great Train Robbery', fullplot: "Among the earliest existing films in American cinema - notable as the first film that presented a narrative story to tell - it depicts a group of cowboy outlaws who hold up a train and rob the passengers. They are then pursued by a Sheriff's posse. Several scenes have color included - all hand tinted.", languages: [ 'English' ], released: ISODate('1903-12-01T00:00:00.000Z'), directors: [ 'Edwin S. Porter' ], rated: 'TV-G', awards: { wins: 1, nominations: 0, text: '1 win.' }, lastupdated: '2015-08-13 00:27:59.177000000', year: 1903, imdb: { rating: 7.4, votes: 9847 }, countries: [ 'USA' ], tomatoes: { viewer: { rating: 3.7, numReviews: 2559, meter: 75 }, fresh: 6, critic: { rating: 7.6, numReviews: 6, meter: 100 }, rotten: 0, lastUpdated: ISODate('2015-08-08T19:16:10.000Z') }, num_mflix_comments: 0 }]

フィールドを除外するには、$unset ステージを使用します。

集計式で変数 REMOVE を使用して、条件付きでフィールドを非表示にできます。

次の $project ステージでは、REMOVE 変数を使用して、imdb.votes フィールドが null と等しいか、空の string である場合にそのフィールドを除外します。

db.movies.aggregate( [ { $match: { title: "This Is Spinal Tap" } }, { $project: { title: 1, "imdb.rating": 1, "imdb.id": 1, "imdb.votes": { $cond: { if: { $in: [ "$imdb.votes", [ null, "" ] ] }, then: "$$REMOVE", else: "$imdb.votes" } } } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1398f29313caabce94a3'), title: 'This Is Spinal Tap', imdb: { rating: 8, id: 88258 } }]

このドキュメントでは imdb.votes は空の文字列であるため、 MongoDB は出力からそのフィールドを除外します。

Tip

$addFields との比較

ドキュメントフィールドを削除するには、$addFields または $project ステージを使用できます。最適なアプローチは、パイプラインと、元のドキュメントをどれだけ保持するかによって異なります。

$addFieldsステージで $$REMOVE を使用する例については、「フィールドの削除」を参照してください。

moviesコレクション内のドキュメントには、rating、votes、id フィールドを持つ埋め込み imdbdocumentが含まれています。To include only the rating フィールド from the imdb document, use ドット表記:

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { "imdb.rating": 1 } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), imdb: { rating: 7.4 } }]

または、インクルージョン指定をdocumentにネストします。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { imdb: { rating: 1 } } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), imdb: { rating: 7.4 } }]

次の $project ステージは、leadActor フィールドと releaseYear フィールドを追加します。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { title: 1, leadActor: { $arrayElemAt: [ "$cast", 0 ] }, releaseYear: "$year" } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), title: 'The Great Train Robbery', leadActor: 'A.C. Abadie', releaseYear: 1903 }]

次の操作では、year フィールドと runtime フィールドを新しい myArrayフィールドの要素としてプロジェクションします。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { myArray: [ "$year", "$runtime" ] } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), myArray: [ 1903, 11 ] }]

配列の指定にドキュメント内に存在しないフィールドが含まれている場合、この操作ではそのフィールドの値として null が置き換えられます。

たとえば、上記と同じドキュメントで次の操作を実行すると、year フィールドと runtime フィールド、および存在しない $someField フィールドが新規フィールドである myArray の要素としてプロジェクトされます。

db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { myArray: [ "$year", "$runtime", "$someField" ] } }, { $limit: 1 }] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), myArray: [ 1903, 11, null ] }]

一般的な集計タスクの詳細については、完全な集計パイプラインチュートリアルをご覧ください。

このページの式と変数について詳しく学ぶには、以下を参照してください。

このページを評価