ドキュメントの検索
Overview
このガイドでは、 MongoDBデータベースからドキュメントを取得する方法を学びます。次の方法を使用して、ドキュメントを見つけることができます。
検索操作を使用してコレクションからドキュメントのサブセットを取得
集計操作を使用して、コレクションから取得されたドキュメントを変換するの実行
変更ストリームを使用してデータベースへのリアルタイム変更をモニタリング
サンプルデータの例
次のセクションでは、塗料店のオーナーが顧客の注文を管理する方法の例を紹介しています。 所有者は注文ごとに、 paint_order
コレクション内の color
とqty
フィールドに対応する色と数量を追跡します。
{ "_id": 1, "color": "purple", "qty": 10 } { "_id": 2, "color": "green", "qty": 8 } { "_id": 3, "color": "purple", "qty": 4 } { "_id": 4, "color": "green", "qty": 11 }
find 操作
検索操作を使用して、 MongoDBからドキュメントを取得します。取得するドキュメント、取得順序、および取得数を指定できます。
指定されたクエリに一致するドキュメントをフィルタリングするには、MongoCollection
のインスタンスで find()
メソッドを呼び出します。クエリを指定する方法の詳細については、「クエリの指定」ガイドを参照してください。
forEach()
次に、 やcursor()
などのメソッドを使用して、一致するドキュメントを取得できます。詳しくは、 FindIterable APIドキュメント を参照してください。
単一ドキュメントを取得するには、find()
呼び出しに first()
メソッドを追加します。特定のドキュメントを選択するには、最初のドキュメントを選択する前に sort()
操作を使用できます。また、メモリ使用量を最適化するために、limit()
メソッドを使用することもできます。詳細については、ソート操作を使用する際のメモリ最適化の詳細については、サーバーのマニュアルを参照してください。
例
所有者は、 patid_order コレクションから、どの注文に 3 缶より多く、9 容量未満の塗料が含まれているかを調べたいと考えています。
このシナリオに対処するために、所有者は条件に一致する注文を見つけます。
Bson filter = Filters.and(Filters.gt("qty", 3), Filters.lt("qty", 9)); // Retrieves documents that match the filter and prints them as JSON collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));
フィルターを構築する方法の詳細については、フィルター ビルダガイドを参照してください。
次に、前のクエリの出力を示します。
{ "_id": 2, "color": "green", "qty": 8 } { "_id": 3, "color": "purple", "qty": 4 }
所有者がこのクエリを実行すると、条件に一致する注文が 2 つ見つかります。
検索例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。 MongoDBインスタンスへの接続の詳細については、「 MongoClient の作成 」ガイドを参照してください。この例では、 Atlasサンプルデータセット に含まれる sample_mflix
データベースの movies
コレクションも使用します。 「 Atlas を使い始める 」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
この例は、次のアクションを実行する完全なスタンドアロンファイルです。
find()
メソッドを呼び出して、runtime
の値が15
分より小さい 10 ドキュメントを検索し、結果にプロジェクションとソートを適用しますfind()
メソッドとfirst()
メソッドを呼び出して、runtime
値が15
分より小さい が最も高いimdb.rating
を持つドキュメントを取得し、結果にプロジェクションを適用します
// Retrieves documents that match a query filter by using the Java driver package org.example; import static com.mongodb.client.model.Filters.lt; import org.bson.Document; import org.bson.conversions.Bson; 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.Projections; import com.mongodb.client.model.Sorts; import static com.mongodb.client.model.Filters.eq; public class Find { 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"); // Projects "title" and "imdb" fields, excludes "_id" Bson projectionFields = Projections.fields( Projections.include("title", "imdb"), Projections.excludeId()); // Retrieves documents with a runtime of less than 15 minutes, applying the // projection and a sorting in alphabetical order FindIterable<Document> docs = collection.find(lt("runtime", 15)) .projection(projectionFields) .sort(Sorts.ascending("title")) .limit(10); // Prints the titles of the queried documents System.out.println("10 movies under 15 minutes: "); docs.forEach(doc -> System.out.println("- " + doc.get("title"))); System.out.println(); // Retrieves the document with the best imdb rating that is less // than 15 minutes long, applying the projection Document doc = collection.find(lt("runtime", 15)) .projection(projectionFields) .sort(Sorts.ascending("imdb.rating")) .first(); // Prints title of the queried document if (doc == null) { System.out.println("No results found."); } else { System.out.println("The highest rated movie under 15 minutes: " + doc.toJson().get("title")); } } } }
10 movies under 15 minutes: 10 Minutes, 3x3, 7:35 in the Morning, 8, 9, A Chairy Tale, A Corner in Wheat, A Gentle Spirit, A Is for Autism, A Movie, The highest rated movie under 15 minutes: {"title": "Andrè and Wally B.", "imdb": {"rating": 5.4, "votes": 3294, "id": 86855}}
集計操作
集計操作を使用して、 集計パイプライン のステージを実行します。 集計パイプラインは、集計結果を生成する複数段階の変換です。
集計操作を実行するには、aggregate()
のインスタンスでMongoCollection
メソッドを呼び出します。このメソッドは、順番に実行される集計式を受け入れます。集計を実行するために、ドキュメントを一致させる方法、フィールドの名前を変更する方法、値をグループ化する方法を指定する集計ステージ を定義できます。詳細については、集計ガイドと「 集計式操作 」のページを参照してください。
例
所有者は、 pattern_order コレクション から最も多く購入された(最も多く販売された)塗料の色を確認したいと考えています。
このシナリオに対処するために、所有者は次のような集計パイプラインを作成します。
paint_order
コレクション内のすべてのドキュメントと一致します注文を色別にグループ化
数量フィールドを色別に合計します
結果を最高数量から最低数量の順に並べ替えます
Bson filter = Filters.empty(); // Prints the collection's "color" values and each value's frequency in descending frequency order collection.aggregate(Arrays.asList( Aggregates.match(filter), Aggregates.group("$color", Accumulators.sum("qty", "$qty")), Aggregates.sort(Sorts.descending("qty")))) .forEach(doc -> System.out.println(doc.toJson()));
次に、前の集計の出力を示します。
{ "_id": "green", "qty": 19 } { "_id": "purple", "qty": 14 }
所有者が集計を実行した後、「緑色」が最も購入された色であることがわかります。
集計パイプラインの構築方法の詳細については、MongoDB Server マニュアルの「集計 」のページを参照してください。
詳細情報
API ドキュメント
このページのドキュメントを検索するために使用されるメソッドとクラスの詳細については、次のAPIドキュメントを参照してください。