Docs Menu
Docs Home
/ / /
Pymongo ドライバー
/ /

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

コレクション内では、異なるドキュメントによって、単一のフィールドの異なる値が含まれる場合があります。 たとえば、ある restaurantドキュメントのborough値は"Manhattan"で、別のドキュメントのborough値は"Queens"です。 PyMongo を使用すると、コレクション内の複数のドキュメントにわたってフィールドに含まれるすべての個別の値を検索できます。

このガイドの例では、 Atlas サンプル データセットsample_restaurants.restaurantsコレクションを使用します。 無料の MongoDB Atlas クラスターを作成し、サンプル データセットをロードする方法については、 PyMongo を使い始める を参照してください。

指定したフィールドの個別の値を検索するには、 distinct()メソッドを呼び出し、個別の値を検索するフィールドの名前を渡します。

次の例では、 restaurantsコレクション内の boroughフィールドの個別の値を取得します。対応するコードを表示するには、Synchronous タブまたは Asynchronousタブを選択します。

results = restaurants.distinct("borough")
for restaurant in results:
print(restaurant)
Bronx
Brooklyn
Manhattan
Missing
Queens
Staten Island
results = await restaurants.distinct("borough")
for restaurant in results:
print(restaurant)
Bronx
Brooklyn
Manhattan
Missing
Queens
Staten Island

結果には、コレクション内のすべてのドキュメントにわたってboroughフィールドに表示されるすべての個別の値が表示されます。 boroughフィールドの値は複数のドキュメントで同じですが、各値は結果に 1 回だけ表示されます。

distinct()メソッドにクエリフィルターを提供すると、コレクション内のドキュメントのサブセット全体で個別のフィールド値を検索できます。 クエリフィルター は、 操作内のドキュメントを照合するために使用される検索条件を指定する 式 です。 クエリフィルターの作成の詳細については、「クエリの指定 」を参照してください。

boroughcuisine次の例では、"Italian" フィールドの個別の値を取得します。対応するコードを表示するには、Synchronous タブまたは Asynchronousタブを選択します。

results = restaurants.distinct("borough", {
"cuisine": "Italian"
})
for restaurant in results:
print(restaurant)
Bronx
Brooklyn
Manhattan
Queens
Staten Island
results = await restaurants.distinct("borough", {
"cuisine": "Italian"
})
for restaurant in results:
print(restaurant)
Bronx
Brooklyn
Manhattan
Queens
Staten Island

distinct()メソッドは、操作を構成するために使用できるオプションを表す任意のパラメーターを受け入れます。 オプションを指定しない場合、ドライバーは操作をカスタマイズしません。

次の表では、 distinct()をカスタマイズするために設定できるオプションについて説明しています。

プロパティ
説明

filter

A query filter that specifies the documents to retrieve distinct values from.

session

An instance of ClientSession.

comment

A comment to attach to the operation.

maxTimeMS

The maximum amount of time to allow the operation to run, in milliseconds.

collation

An instance of Collation.

次の例では、name boroughフィールドフィールドが"Bronx" cuisineであるすべてのドキュメントの"Pizza" フィールドの個別の値を取得します。また、 comment オプションを使用して操作にコメントを追加します。対応するコードを表示するには、Synchronous タブまたは Asynchronousタブを選択します。

results = restaurants.distinct("name",
{ "borough": "Bronx",
"cuisine": "Pizza" },
comment="Bronx pizza restaurants"
)
$1.25 Pizza
18 East Gunhill Pizza
2 Bros
Aenos Pizza
Alitalia Pizza Restaurant
...
results = await restaurants.distinct("name",
{ "borough": "Bronx",
"cuisine": "Pizza" },
comment="Bronx pizza restaurants"
)
$1.25 Pizza
18 East Gunhill Pizza
2 Bros
Aenos Pizza
Alitalia Pizza Restaurant
...

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。

戻る

ドキュメントをカウント

項目一覧