Overview
このガイドでは、 Rubyドライバーを使用して、コレクション全体で指定されたフィールドの個別の値を検索する方法を学習できます。
コレクション内では、ドキュメントには単一のフィールドに異なる値が含まれる場合があります。例、restaurants
コレクション内の 1 つのドキュメントの borough
値は 'Manhattan'
で、別のドキュメントの borough
値は 'Queens'
です。Rubyドライバーを使用すると、コレクション内の複数のドキュメントにわたってフィールドに含まれるすべての一意の値を検索できます。
サンプル データ
このガイドの例では、 Atlasサンプルデータセット の sample_restaurants
データベースの restaurants
コレクションを使用します。Rubyアプリケーションからこのコレクションにアクセスするには、Atlas クラスターに接続する Mongo::Client
オブジェクトを作成し、次の値を database
変数と collection
変数に割り当てます。
database = client.use('sample_restaurants') collection = database[:restaurants]
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
Retrieve Distinct Values
指定したフィールドの個別の値を検索するには、 distinct
メソッドを呼び出し、個別の値を検索するフィールドの名前を渡します。
コレクション全体で値を取得
次の例では、 restaurants
コレクション内のborough
フィールドの個別の値を取得します。
results = collection.distinct('borough') results.each do |value| puts value end
Bronx Brooklyn Manhattan Missing Queens Staten Island
この操作では、個別のborough
フィールド値をそれぞれ保存する配列が返されます。 borough
フィールドでは複数のドキュメントが同じ値になっていますが、各値は結果に 1 回だけ表示されます。
指定されたドキュメント全体で値を取得
distinct
メソッドにクエリフィルターを提供すると、コレクション内のドキュメントのサブセット全体で個別のフィールド値を検索できます。クエリフィルターは、操作内のドキュメントを一致させるために使用される検索条件を指定する式です。
Tip
クエリフィルターの作成の詳細については、クエリの指定ガイドを参照してください。
次の例では、 cuisine
フィールドの値が'Italian'
であるすべてのドキュメントのborough
フィールドの個別の値を取得します。
results = collection.distinct('borough', { cuisine: 'Italian' }) results.each do |value| puts value end
Bronx Brooklyn Manhattan Queens Staten Island
個別の動作の変更
オプション値を指定する Hash
オブジェクトを渡すことで、distinct
メソッドの動作を変更できます。次の表では、操作をカスタマイズするために設定できるオプションについて説明します。
オプション | 説明 |
---|---|
| The collation to use for the operation. Type: Hash |
| The maximum amount of time in milliseconds that the operation can run. Type: Integer |
| The read preference to use for the operation. To learn more, see
Read Preference in the MongoDB Server manual. Type: Hash |
| The session to use for the operation. Type: Session |
次の例では、name
borough
フィールドフィールドが'Bronx'
cuisine
であるすべてのドキュメントの'Pizza'
フィールドの個別の値を取得します。また、read
オプションも設定され、これは操作にprimary_preferred
読み込み設定 (read preference)を使用するように指示します。
filter = { borough: 'Bronx', cuisine: 'Pizza' } options = { read: { mode: :primary_preferred } } results = collection.distinct('name', filter, options) results.each do |value| puts value end
$1.25 Pizza 18 East Gunhill Pizza 2 Bros Aenos Pizza Alitalia Pizza Restaurant Amici Pizza And Pasta Angie'S Cafe Pizza Anthony & Joe'S Pizza Anthony'S Pizza Antivari Pizza Arturo'S Pizza Bartow Pizza ...
API ドキュメント
distinct
メソッドの詳細については、APIドキュメントを参照してください。