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

クエリ

このページでは、 PyMongoでドキュメントを検索するために使用できる一般的な方法を示すコピー可能なコード例を紹介します。

Tip

このページに記載されているメソッドの詳細については、各セクションに提供されているリンクを参照してください。

このページの例を使用するには、コード例をサンプル アプリケーションまたは独自のアプリケーションにコピーします。 <connection string URI>など、コード例にあるすべてのプレースホルダーを、MongoDB 配置に関連する値に置き換えてください。

次のサンプルアプリケーションを使用して、このページのコード例をテストできます。 サンプル アプリケーションを使用するには、次の手順を実行します。

  1. PyMongo がインストールされていることを確認します。

  2. 次のコードをコピーし、新しい.pyファイルに貼り付けます。

  3. このページからコード例をコピーし、 ファイル内の指定された行に貼り付けます。

対応するコードを表示するには、Synchronous タブまたは Asynchronousタブを選択します。

1import pymongo
2from pymongo import MongoClient
3
4try:
5 uri = "<connection string URI>"
6 client = MongoClient(uri)
7
8 database = client["<database name>"]
9 collection = database["<collection name>"]
10
11 # start example code here
12
13 # end example code here
14
15 client.close()
16
17except Exception as e:
18 raise Exception(
19 "The following error occurred: ", e)
1import asyncio
2import pymongo
3from pymongo import AsyncMongoClient
4
5async def main():
6 try:
7 uri = "<connection string URI>"
8 client = AsyncMongoClient(uri)
9
10 database = client["<database name>"]
11 collection = database["<collection name>"]
12
13 # start example code here
14
15 # end example code here
16
17 await client.close()
18
19 except Exception as e:
20 raise Exception(
21 "The following error occurred: ", e)
22
23asyncio.run(main())
results = collection.find_one({ "<field name>" : "<value>" })
print(results)
results = await collection.find_one({ "<field name>" : "<value>" })
print(results)

find_one()メソッドの詳細については、データ取得ガイドの「1 つのドキュメントを検索する 」を参照してください。

results = collection.find({ "<field name>" : "<value>" })
for document in results:
print(document)
results = collection.find({ "<field name>" : "<value>" })
async for document in results:
print(document)

find()メソッドの詳細については、データ取得 ガイドの「 複数のドキュメントの検索 」を参照してください。

count = collection.count_documents({})
print(count)
count = await collection.count_documents({})
print(count)

count_documents()メソッドの詳細については、「正確なカウントの取得」ガイドを参照してください。

count = collection.count_documents({ "<field name>": "<value>" })
print(count)
count = await collection.count_documents({ "<field name>": "<value>" })
print(count)

count_documents()メソッドの詳細については、「正確なカウントの取得」ガイドを参照してください。

count = collection.estimated_document_count()
print(count)
count = await collection.estimated_document_count()
print(count)

estimated_document_count()メソッドの詳細については、「推定カウントの取得」ガイドを参照してください。

results = collection.distinct("<field name>")
for document in results:
print(document)
results = await collection.distinct("<field name>")
for document in results:
print(document)

distinct()メソッドの詳細については、「個別のフィールド値の取得 」ガイドを参照してください。

with collection.watch() as stream:
for change in stream:
print(change)
async with await collection.watch() as stream:
async for change in stream:
print(change)

watch() メソッドの詳細については、Change Streams によるデータの監視 ガイドを参照してください。

戻る

ドキュメントの挿入

項目一覧