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

プロジェクション ビルダ

このガイドでは、MongoDB Java ドライバーで ビルダ を使用して プロジェクション を指定する方法を学びます。

MongoDB はフィールドプロジェクションをサポートしており、クエリから結果を返すときに含めるフィールドと除外するフィールドを指定します。 MongoDB のプロジェクションは、いくつかの基本的なルールに従います。

  • _idフィールドは明示的に除外されない限り、常に含まれます

  • 含めるフィールドを指定すると、 _idフィールドを除く他のすべてのフィールドが暗黙的に除外されます

  • 除外するフィールドを指定すると、クエリ結果内のそのフィールドのみが削除されます

プロジェクションの仕組みの詳細については、こちらをご覧ください。

Projectionsクラスは、すべての MongoDB プロジェクション演算子の静的ファクトリー メソッドを提供します。 各メソッドはBSON型のインスタンスを返します。このインスタンスは、プロジェクションを必要とする任意のメソッドに渡すことができます。

Tip

簡潔にするために、 Projectionsクラスのメソッドを静的にインポートすることを選択できます。

import static com.mongodb.client.model.Projections.*;

次の例では、この静的インポートを前提としています。

次のセクションでは、 projection_buildersというサンプル コレクションに対してクエリとプロジェクション操作を実行する例を紹介します。 各セクションでは、 collectionという名前の変数を使用して、 projection_buildersコレクションのMongoCollectionインスタンスを参照します。

コレクションには、2018 年と 2019 年の月間平均温度を摂氏単位で表す次のドキュメントが含まれています。

{ "year" : 2018, "type" : "even number but not a leap year", "temperatures" : [ { "month" : "January", "avg" : 9.765 }, { "month" : "February", "avg" : 9.675 }, { "month" : "March", "avg" : 10.004 }, { "month" : "April", "avg" : 9.983 }, { "month" : "May", "avg" : 9.747 }, { "month" : "June", "avg" : 9.65 }, { "month" : "July", "avg" : 9.786 }, { "month" : "August", "avg" : 9.617 }, { "month" : "September", "avg" : 9.51 }, { "month" : "October", "avg" : 10.042 }, { "month" : "November", "avg" : 9.452 }, { "month" : "December", "avg" : 9.86 } ]},{ "year" : 2019, "type" : "odd number, can't be a leap year", "temperatures" : [ { "month" : "January", "avg" : 10.023 }, { "month" : "February", "avg" : 9.808 }, { "month" : "March", "avg" : 10.43 }, { "month" : "April", "avg" : 10.175 }, { "month" : "May", "avg" : 9.648 }, { "month" : "June", "avg" : 9.686 }, { "month" : "July", "avg" : 9.794 }, { "month" : "August", "avg" : 9.741 }, { "month" : "September", "avg" : 9.84 }, { "month" : "October", "avg" : 10.15 }, { "month" : "November", "avg" : 9.84 }, { "month" : "December", "avg" : 10.366 } ]}

次のセクションには、利用可能なプロジェクション操作と、 Projectionsクラスを使用してそれらを構築する方法に関する情報が記載されています。

1 つ以上のフィールドを含めるように指定するには、 include()メソッドを使用します。

次の例には、 yearフィールドと(暗黙的に) _idフィールドが含まれています。

Bson filter = Filters.empty();Bson projection = include("year");collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"_id": {"$oid": "6042edc9f2b56342164e0790"}, "year": 2018}{"_id": {"$oid": "6042edc9f2b56342164e0791"}, "year": 2019}

次の例には、 yearフィールドとtypeフィールド、および(暗黙的に) _idフィールドが含まれています。

Bson filter = Filters.empty();Bson projection = include("year", "type");collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"_id": {"$oid": "6042edc9f2b56342164e0790"}, "year": 2018, "type": "even number but not a leap year"}{"_id": {"$oid": "6042edc9f2b56342164e0791"}, "year": 2019, "type": "odd number, can't be a leap year"}

1 つ以上のフィールドの除外を指定するには、 exclude()メソッドを使用します。

次の例では、 temperaturesフィールドが除外されています。

Bson filter = Filters.empty();Bson projection = exclude("temperatures");collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"_id": {"$oid": "6042edc9f2b56342164e0790"}, "year": 2018, "type": "even number but not a leap year"}{"_id": {"$oid": "6042edc9f2b56342164e0791"}, "year": 2019, "type": "odd number, can't be a leap year"}

次の例では、type フィールドとtemperatures フィールドが除外されています。

Bson filter = Filters.empty();Bson projection = exclude("temperatures", "type");collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"_id": {"$oid": "6042edc9f2b56342164e0790"}, "year": 2018}{"_id": {"$oid": "6042edc9f2b56342164e0791"}, "year": 2019}

複数のプロジェクションを結合するには、 fields()メソッドを使用します。

次の例には、 yearフィールドとtypeフィールドが含まれ、 _idフィールドは除外されています。

Bson filter = Filters.empty();Bson projection = fields(include("year", "type"), exclude("_id"));collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"year": 2018, "type": "even number but not a leap year"}{"year": 2019, "type": "odd number, can't be a leap year"}

excludeId()便利メソッドを使用して、 _idフィールドの除外を指定します。

Bson filter = Filters.empty();Bson projection = fields(include("year", "type"), excludeId());collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"year": 2018, "type": "even number but not a leap year"}{"year": 2019, "type": "odd number, can't be a leap year"}

elemMatch(String, Bson)メソッド バリアントを使用して、指定されたクエリフィルターに一致する配列の最初の要素を含む配列プロジェクションを指定します。 このフィルタリングは、クエリフィルター(指定された場合)に一致するすべてのドキュメントが取得された後に発生します。

注意

一致の数に関係なく、指定されたクエリフィルターに一致する最初の要素のみが含まれます。

次の例えでは、 avgフィールドが10.1より大きいtemperatures配列の最初の要素をプロジェクトします。

Bson filter = Filters.empty();Bson projection = fields(include("year"), elemMatch("temperatures", Filters.gt("avg", 10.1)));collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"_id": {"$oid": "6042edc9f2b56342164e0790"}, "year": 2018}{"_id": {"$oid": "6042edc9f2b56342164e0791"}, "year": 2019, "temperatures": [{"month": "March", "avg": 10.43}]}

操作のクエリ部分で一致条件を指定した場合、 elemMatch(String)メソッド バリアントを使用して、配列の最初の要素を含める位置プロジェクションを指定します。 クエリフィルターに一致するドキュメントのみが検索されます。

重要

MongoDB バージョン 4.4 未満では、指定された配列フィールドがクエリフィルターに表示される必要があります。 MongoDB 4.4 以降では、クエリフィルターに表示されない配列フィールドで位置プロジェクトを使用できます。

次の例えでは、 temperatures配列の最初の要素をプロジェクションします。

Bson filter = Filters.gt("temperatures.avg", 10.1);Bson projection = fields(include("year"), elemMatch("temperatures"));collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"_id": {"$oid": "6042edc9f2b56342164e0791"}, "year": 2019, "temperatures": [{"month": "March", "avg": 10.43}]}

配列のスライスをプロジェクションするには、 slice()メソッドを使用します。

次の例では、 temperatures配列の最初の6 つの要素をプロジェクションします。

Bson filter = Filters.empty();// first half of the yearBson projection = slice("temperatures", 6);collection.find(filter).projection(projection) .forEach(doc -> System.out.println(doc.toJson(JsonWriterSettings.builder().indent(true).build())));

次のコードは、このプロジェクションの 出力を示しています。

{ "_id": { "$oid": "6042f1bc8ee6fa2a84d2be69" }, "year": 2018, "type": "even number but not a leap year", "temperatures": [ ... <January-June temperature nested documents> ]}{ "_id": { "$oid": "6042f1bc8ee6fa2a84d2be6a" }, "year": 2019, "type": "odd number, can't be a leap year", "temperatures": [ ... <January-June temperature nested documents> ]}

次の例では、 temperatures配列の最初の6 つの要素をスキップし、次の6つのプロジェクションをプロジェクションします。

Bson filter = Filters.empty();// second half of the yearBson projection = slice("temperatures", 6, 6);collection.find(filter).projection(projection) .forEach(doc -> System.out.println(doc.toJson(JsonWriterSettings.builder().indent(true).build())));

次のコードは、このプロジェクションの 出力を示しています。

{ "_id": { "$oid": "6042f1bc8ee6fa2a84d2be69" }, "year": 2018, "type": "even number but not a leap year", "temperatures": [ ... <July-December temperature nested documents> ]}{ "_id": { "$oid": "6042f1bc8ee6fa2a84d2be6a" }, "year": 2019, "type": "odd number, can't be a leap year", "temperatures": [ ... <July-December temperature nested documents> ]}

テキスト クエリのスコアのプロジェクションを指定するには、 metaTextScore()メソッドを使用します。

次の例では、テキスト スコアをscoreフィールドの値としてプロジェクションします。

Bson filter = Filters.text("even number");Bson projection = fields(include("year"), metaTextScore("score"));collection.find(filter).projection(projection).forEach(doc -> System.out.println(doc.toJson()));

次のコードは、このプロジェクションの 出力を示しています。

{"_id": {"$oid": "6042f1bc8ee6fa2a84d2be69"}, "year": 2018, "score": 1.25}{"_id": {"$oid": "6042f1bc8ee6fa2a84d2be6a"}, "year": 2019, "score": 0.625}