Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Java Sync Driver
/ /

フィールドの個別の値を取得

このガイドでは、MongoCollectionオブジェクトで distinct() メソッドを呼び出して、コレクション全体のフィールドの個別の値のリストを取得する方法を学びます。以下のように、最初のパラメーターとしてドキュメントフィールド名を渡し、2 番目のパラメーターとして結果に使用するクラスを渡します。

collection.distinct("countries", String.class);

You can specify a field on the document or one within an embedded document using dot notation. 次のメソッド呼び出しは、 awards埋め込みドキュメントのwinsフィールドのそれぞれの値を返します。

collection.distinct("awards.wins", Integer.class);

オプションで、 メソッドにクエリフィルターを渡して、MongoDB インスタンスが個別の値を取得するドキュメントのセットを制限できます。

collection.distinct("type", Filters.eq("languages", "French"), String.class);

distinct()メソッドは、 DistinctIterableインターフェースを実装するオブジェクトを返します。 このインターフェースには、結果にアクセスし、整理し、走査するためのメソッドが含まれています。 また、最初の結果を返す や のインスタンスを返す など、親インターフェースMongoIterable first()cursor()MongoCursorからメソッドも継承します。

次のスニペットは、 moviesコレクションからyearドキュメント フィールドの個別の値のリストを取得します。 クエリフィルターを使用して、 directors配列の値の 1 つとして "Charl Atlas" を含む映画を照合します。

注意

この例では、接続 URI を使用して MongoDB のインスタンスに接続します。 MongoDB インスタンスへの接続の詳細については、「 接続ガイド 」を参照してください。

// Retrieves distinct values of a field by using the Java driver
package usage.examples;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class Distinct {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// Retrieves the distinct values of the "year" field present in documents that match the filter
DistinctIterable<Integer> docs = collection.distinct("year", Filters.eq("directors", "Carl Franklin"), Integer.class);
MongoCursor<Integer> results = docs.iterator();
// Prints the distinct "year" values
while(results.hasNext()) {
System.out.println(results.next());
}
}
}
}

例を実行すると、カーネル フランクリンクが監督として含まれたすべての映画について、それぞれの年ごとに報告する次のような出力が表示されます。

1992
1995
1998
...

Tip

Legacy API

レガシーAPIを使用している場合は、この コード例に加える必要がある変更について、レガシーAPIガイドのFAQセクションを参照してください。

このページで言及されているクラスとメソッドについて詳しくは、次のリソースを参照してください。

  • distinct() APIドキュメント

  • DistingIterable API ドキュメント

  • ドット表記サーバー マニュアル入力

  • MongoIterable API ドキュメント

戻る

ドキュメントをカウント

項目一覧