定義
互換性
次の環境でホストされる配置には $project を使用できます。
MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
$projectステージのプロトタイプ形式は次のとおりです。
{ $project: { <specification(s)> } }
$project が受け入れるドキュメントでは、含めるフィールド、非表示にする _id フィールド、新たに加えるフィールド、値をリセットする既存フィールドの指定が可能です。除外するフィールドを指定することもできます。
$project の指定形式は次のとおりです。
フォーム | 説明 |
|---|---|
| フィールドを含めるかどうかを指定します。ゼロ以外の整数も |
|
条件付きでフィールドを除外するには、代わりに |
| 新規フィールドを追加するか、既存フィールドの値をリセットします。 式が |
| フィールドの除外を指定します。 条件付きでフィールドを除外するには、代わりに
フィールドを除外するには、 |
動作
含めるフィールドの指定
_id フィールド
_id フィールドはデフォルトで出力ドキュメントに含まれます。出力ドキュメントから _id フィールドを除外するには、$project で _id フィールドの非表示を指定します。
フィールドの除外
1 つまたは複数のフィールドを除外するように指定すると、他のすべてのフィールドが出力ドキュメントに返されます。
{ $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 ステージを使用する場合、通常このステージをパイプラインの最後のステージにして、クライアントに返すフィールドを指定するために使用します。
$project ステージをパイプラインの開始または中間で使用して、後続のパイプラインステージに渡されるフィールドの数を減らしてもパフォーマンスが改善する可能性はほとんどありません。データベースではこの最適化が自動的に実行されているためです。
Considerations
空の仕様
MongoDB は、$project ステージが空のドキュメントとして渡される場合、エラーを返します。
たとえば、次のパイプラインを実行するとエラーが発生します。
db.myCollection.aggregate( [ { $project: { } } ] )
Array Index
$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' } ]
出力ドキュメントの _id フィールドを非表示にする
MongoDB にはデフォルトで_id フィールドが含まれています。_id ステージから$project フィールドを除外するには、プロジェクションドキュメントで フィールドを_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.votesnullと等しい、または空の文字列である場合、 変数を使用して フィールドを除外します。
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コレクション内のドキュメントには、imdb ratingvotesid、 、 フィールドを持つ埋め込み ドキュメントが含まれています。 ドキュメントの フィールドのみを含めるには、ドット表記を使用します。ratingimdb
db.movies.aggregate( [ { $match: { title: "The Great Train Robbery" } }, { $project: { "imdb.rating": 1 } }, { $limit: 1 } ] )
[ { _id: ObjectId('573a1390f29313caabcd42e8'), imdb: { rating: 7.4 } } ]
または、インクルージョン指定をドキュメントにネストします。
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 ] } ]
このページのC#の例では、Atlasサンプルデータセット の sample_mflixデータベースを使用します。MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 MongoDB .NET/ C#ドライバーのドキュメントの「 開始 」を参照してください。
次の Movie クラスと ImdbData クラスは、sample_mflix.moviesコレクション内のドキュメントをモデル化します。
public class Movie { public ObjectId Id { get; set; } public string Title { get; set; } public List<string> Genres { get; set; } public List<string> Directors { get; set; } public List<string> Writers { get; set; } public string Type { get; set; } public string Plot { get; set; } public ImdbData Imdb { get; set; } public List<string> Cast { get; set; } }
public class ImdbData { public string Id { get; set; } public int Votes { get; set; } public float Rating { get; set; } }
注意
パスカルケースの ConventionPack
このページのC# クラスはプロパティ名にパスカルケースを使用していますが、MongoDB コレクションのフィールド名はキャメルケースを使用しています。この違いを考慮するために、アプリケーションが起動する際に次のコードを使用してConventionPackを登録してください。
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
MongoDB .NET/C# ドライバーを使用して $project ステージを集計パイプラインに追加するには、PipelineDefinition オブジェクトで Project() メソッドを呼び出し、ProjectionDefinitionBuilder<TDocument> オブジェクトを渡します。TDocument は、コレクション内のドキュメントを表すクラスです。
次のセクションでは、$project ステージの出力ドキュメントをカスタマイズするさまざまな方法を示します。
出力ドキュメントへの特定のフィールドの追加
.NET/C# ドライバーを使用する際に特定のフィールドを含めるには、プロジェクション ビルダの Include() メソッドを呼び出します。複数のフィールドを含めるために、Include() 呼び出しを連鎖させることができます。
次のコード例では、_id フィールド、plot フィールド、および title フィールドのみを含むドキュメントが生成されます。
var pipeline = new EmptyPipelineDefinition<Movie> () .Project( Builders<Movie>.Projection .Include(m => m.Title) .Include(m => m.Plot) ); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
パイプラインは次のドキュメントを返します。
{ "_id" : { "$oid" : "573a1390f29313caabcd42e8" }, "plot" : "A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.", "title" : "The Great Train Robbery" }
出力ドキュメントからのフィールドの除外
.NET/C# ドライバーを使用して結果ドキュメントからフィールドを除外するには、プロジェクション ビルダの Exclude() メソッドを呼び出します。複数のフィールドを除外するために、Exclude() 呼び出しを連鎖させることができます。
次のコード例は、Type フィールドを除外したドキュメントを生成します。
var pipeline = new EmptyPipelineDefinition<Movie>() .Project( Builders<Movie>.Projection .Exclude(m => m.Type) ); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
デフォルトでは、結果ドキュメントには常に _id フィールドが含まれます。次のコード例では、_id フィールドを除外し、plot フィールドと title フィールドを含むドキュメントを生成します。
var pipeline = new EmptyPipelineDefinition<Movie> () .Project( Builders<Movie>.Projection .Exclude(m => m.Id) .Include(m => m.Title) .Include(m => m.Plot) ); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
パイプラインは次のドキュメントを生成します。
{ "plot" : "A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.", "title" : "The Great Train Robbery" }
埋め込みドキュメントからフィールドを除外する場合
.NET/C# ドライバーを使用して埋め込みドキュメントからフィールドを除外するには、プロジェクション ビルダの Exclude() メソッドを呼び出し、対応するクラス プロパティへのパスを渡します。複数のフィールドを除外するために、Exclude() 呼び出しを連鎖させることができます。
次のコード例は、imdb.id フィールドと type フィールドを除外するドキュメントを生成します。
var pipeline = new EmptyPipelineDefinition<Movie> () .Project( Builders<Movie>.Projection .Exclude("Imdb.id") .Exclude(m => m.Type) ); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
パイプラインの結果として、次の出力が得られます。
{ "plot" : "A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.", "title" : "The Great Train Robbery", ... "imdb" : { "rating" : 7.4000000000000004, "votes" : 9847 } }
注意
埋め込み ID フィールドには文字列を使用
埋め込みドキュメントに ID フィールドをプロジェクトするには、フィールド名を lambda 式ではなく string として指定します。
フィールドの条件付き除外
集計式で変数 REMOVE を使用して、条件付きでフィールドを非表示にできます。
var stage = new BsonDocument { { "title", 1 }, { "imdb.id", 1 }, { "imdb.rating", 1 }, { "imdb.votes", new BsonDocument("$cond", new BsonDocument { { "if", new BsonDocument("$eq", new BsonArray { "", "$imdb.votes" }) }, { "then", "$$REMOVE" }, { "else", "$imdb.votes" } }) } }; var pipeline = new EmptyPipelineDefinition<Movie>() .Project(stage) .Sample(1); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
注意
条件付き除外のためのビルダがありません
前述の例では、.NET/C# ドライバーが条件付きでフィールドを除外するビルダを提供しないため、BsonDocument オブジェクトを使用しています。他の MongoDB 言語ドライバーがこの機能をサポートしている可能性があります。詳細については、「MongoDB ドライバーのドキュメント」をご覧ください。
サンプリングされたドキュメントに imdb.votes フィールドが含まれている場合、パイプラインは以下のようなドキュメントを返します。
{ "_id" : { "$oid" : "573a1390f29313caabcd42e8" }, "title" : "The Great Train Robbery", "imdb" : { "rating" : 7.4000000000000004, "id" : 439, "votes" : 9847 } }
ドキュメントに imdb.votes フィールドが含まれていない場合、パイプラインは次のようなドキュメントを返します。
{ "_id" : { "$oid" : "573a1398f29313caabce94a3" }, "title" : "This Is Spinal Tap", "imdb" : { "rating" : 8.0, "id" : 88258 } }
計算フィールドの追加
.NET/C# ドライバーを使用して結果ドキュメントに計算されたフィールドを含めるするには、プロジェクション ビルダの Expression() メソッドを呼び出し、計算されたフィールドを含む式を渡します。型の安全性を高めるために、次の ProjectedMovie クラスのように、結果ドキュメントのモデル クラスを定義することができます。
public class ProjectedMovie { public ObjectId Id { get; set; } public string Title { get; set; } public string LeadActor { get; set; } public List<string> Crew { get; set; } }
次のコード例は、複数の計算フィールドを含むドキュメントを生成します。
var pipeline = new EmptyPipelineDefinition<Movie>() .Project( Builders<Movie> .Projection .Expression(m => new ProjectedMovie { Id = m.Id, Title = m.Title, LeadActor = m.Cast[0], }) ); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
パイプラインは次のドキュメントを生成します。
{ "_id" : { "$oid" : "573a1390f29313caabcd42e8" }, "title" : "The Great Train Robbery", "leadActor" : "A.C. Abadie", ... }
新しい配列フィールドのプロジェクト
.NET/C# ドライバーを使用して結果ドキュメントに新しい配列フィールドをプロジェクトするには、プロジェクション ビルダの Expression() メソッドを呼び出し、新しい配列フィールドを含む式を渡します。型の安全性を高めるために、次の ProjectedMovie クラスのように、結果ドキュメントのモデル クラスを定義することができます。
public class ProjectedMovie { public ObjectId Id { get; set; } public string Title { get; set; } public string LeadActor { get; set; } public List<string> Crew { get; set; } }
次のコード例は、directors フィールドと writers フィールドの値を含む、新しい配列フィールド crew を含むドキュメントを生成します。
var pipeline = new EmptyPipelineDefinition<Movie> () .Project( Builders<Movie> .Projection .Expression(m => new ProjectedMovie { Id = m.Id, Title = m.Title, LeadActor = m.Cast[0], Crew = m.Directors.Concat(m.Writers).ToList() } ) ) .Sample(1); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
パイプラインは、次のようなドキュメントを返します。
{ "_id" : { "$oid" : "573a1395f29313caabce2297" }, "title" : "The Chalk Garden", "leadActor" : "Deborah Kerr", "crew" : ["Ronald Neame", "John Michael Hayes (screenplay)", "Enid Bagnold (from the play by)"] }
配列の指定にドキュメント内に存在しないフィールドが含まれている場合、このパイプラインではそのフィールドの値としてnullを置き換えます。たとえば、次のコード例では、フィールド directors、writers、および存在しないフィールド makeupArtistsを、crewという名前の新しいフィールドの要素としてプロジェクトします。
var stage = new BsonDocument { { "crew", new BsonArray { "$directors", "$writers", "$makeupArtists" } } }; var pipeline = new EmptyPipelineDefinition<Movie>() .Project(stage) .Sample(1); var result = movieCollection.Aggregate(pipeline).FirstOrDefault();
パイプラインは、次のようなドキュメントを返します。
{ "_id" : { "$oid" : "573a1399f29313caabced0d9" }, "crew" : [["Bill Kroyer"], ["Jim Cox (screenplay)", "Diana Young (original stories)"], null] }
注意
フィールドの欠落を防ぐビルダ クラス
前述の例では BsonDocument オブジェクトを使用しています。これは、ビルダを使用して欠落しているフィールドを配列に追加しようとすると、.NET/C#ドライバーがコンパイル時エラーを発生させるためです。他の MongoDB 言語ドライバーがこの機能をサポートしている可能性があります。詳細については、「MongoDB ドライバーのドキュメント」をご覧ください。
このページのNode.js の例では、Atlasサンプルデータセット の sample_mflixデータベースを使用します。無料のMongoDB Atlas cluster を作成し、サンプルデータセットをロードする方法については、 MongoDB Node.jsドライバーのドキュメントの開始を参照してください。
MongoDB Node.jsドライバーを使用して $project ステージを集計パイプラインに追加するには、パイプラインオブジェクトで $project 演算子を使用します。
次のセクションでは、$project ステージの出力ドキュメントをカスタマイズする方法を示します。
出力ドキュメントへの特定のフィールドの追加
特定のフィールドを含めるには、$project段階でフィールドの値を1に設定してください。
次の例では、_id、plot、および title フィールドのみを含むドキュメントが返されます。
const pipeline = [ { $project: { title: 1, plot: 1 } } ]; const cursor = collection.aggregate(pipeline); return cursor;
出力ドキュメントは次の例のようになります。
{ _id: new ObjectId('573a1390f29313caabcd42e8'), plot: 'A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.', title: 'The Great Train Robbery' }
出力ドキュメントからのフィールドの除外
特定のフィールドを除外するには、$project ステージでフィールドの値を 0 に設定してください。
次の例では、type フィールドを除外したドキュメントを返します。
const pipeline = [ { $project: { type: 0 } } ]; const cursor = collection.aggregate(pipeline); return cursor;
デフォルトでは、結果ドキュメントには常に _id フィールドが含まれます。次の例では、_id フィールドを除外し、plot フィールドと title フィールドを含むドキュメントを返します。
const pipeline = [ { $project: { _id: 0, title: 1, plot: 1 } } ]; const cursor = collection.aggregate(pipeline); return cursor;
出力ドキュメントは次の例のようになります。
{ plot: 'A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.', title: 'The Great Train Robbery' }
埋め込みドキュメントからフィールドを除外する場合
埋め込みドキュメントからフィールドを除外するには、$project ステージでフィールドパスの値を 0 に設定します。
注意
埋め込みフィールドに文字列を使用する
埋め込みドキュメントのフィールドをプロジェクトするには、フィールドパスを string として指定します。
次の例では、imdb.id および type フィールドを除外したドキュメントが返されます。
const pipeline = [ { $project: { "imdb.id": 0, type: 0 } } ]; const cursor = collection.aggregate(pipeline); return cursor;
出力ドキュメントは次の例のようになります。
{ plot: 'A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.', title: 'The Great Train Robbery', imdb: { rating: 7.4000000000000004, votes: 9847 } }
フィールドの条件付き除外
フィールドを条件付きで除外するには、変数 REMOVEを含む条件ロジックをフィールド名に割り当てます。
const pipeline = [ { $project: { title: 1, "imdb.id": 1, "imdb.rating": 1, "imdb.votes": { $cond: { if: { $eq: ["$imdb.votes", ""] }, then: "$REMOVE", else: "$imdb.votes" } } } } ]; const cursor = collection.aggregate(pipeline); return cursor;
ドキュメントに imdb.votes フィールドが含まれている場合、パイプラインは次の例のような出力を返します。
{ _id: new ObjectId('573a1390f29313caabcd42e8'), title: 'The Great Train Robbery', imdb: { rating : 7.4000000000000004, id: 439, votes: 9847 } }
ドキュメントに imdb.votes フィールドが含まれていない場合、パイプラインは以下の例のようなドキュメントを返します。
{ _id: new ObjectId('573a1390f29313caabcd42e8'), title: 'This Is Spinal Tap', imdb: { rating: 8.0, id: 88258 } }
計算フィールドの追加
結果のドキュメントに計算されたフィールドを含めるには、結果を保存するフィールドに式を割り当てます。
次の例では、_id フィールドと title フィールドを同じ名前の新規フィールドにプロジェクトし、新規フィールド leadActor を計算します。この例では、これらのフィールドを含むドキュメントが返されます。
const pipeline = [ { $project: { _id: "$_id", title: "$title", leadActor: { $arrayElemAt: ["$cast", 0] } } } ]; const cursor = collection.aggregate(pipeline); return cursor;
出力ドキュメントは次の例のようになります。
{ _id: new ObjectId('573a1390f29313caabcd42e8'), title: 'The Great Train Robbery', leadActor: 'A.C. Abadie' }
新しい配列フィールドのプロジェクト
結果ドキュメントに新しい配列フィールドをプロジェクトするには、新しい配列フィールドを計算する式を配列を保存するフィールドに割り当てます。
次の例では、directors フィールドと writers フィールドの値を組み合わせた新しい配列フィールド crew を含むドキュメントを返します。
const pipeline = [ { $project: { _id: "$_id", title: "$title", leadActor: { $arrayElemAt: ["$cast", 0] }, crew: { $concatArrays: ["$directors", "$writers"] } } } ]; const cursor = collection.aggregate(pipeline); return cursor;
出力ドキュメントは次の例のようになります。
{ _id: new ObjectId('573a1395f29313caabce2297'), title: 'The Chalk Garden', leadActor: 'Deborah Kerr', crew: ['Ronald Neame', 'John Michael Hayes (screenplay)', 'Enid Bagnold (from the play by)'] }
配列の指定にドキュメントに存在しないフィールドが含まれている場合、このパイプラインではそのフィールドの値として null を置き換えます。たとえば、次のコード例では、フィールド directors、writers、および存在しないフィールドmakeupArtists を、 crew という名前の新しいフィールドの要素としてプロジェクトします。
const pipeline = [ { $project: { crew: ["$directors", "$writers", "$makeupArtists"] } } ]; const cursor = collection.aggregate(pipeline); return cursor;
出力ドキュメントは次の例のようになります。
{ _id: new ObjectId('573a1399f29313caabced0d9'), crew: [['Bill Kroyer'], ['Jim Cox (screenplay)', 'Diana Young (original stories)'], null] }
詳細
一般的な集計タスクの詳細情報と説明については、完全な集計パイプラインチュートリアルをご覧ください。
このページのメソッドの詳細については、以下のガイドを参照してください。