Skip to content

DOCSP-48163: Add async examples for Read pages #227

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions source/includes/cursors/cursors-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# start-cursor-iterate
results = collection.find()

async for document in results:
print(document)
# end-cursor-iterate

# start-cursor-next
results = collection.find({ "name": "Dunkin' Donuts" })

print(await results.next())
# end-cursor-next

# start-cursor-list
results = collection.find({ "name": "Dunkin' Donuts" })

all_results = await to_list(results)

for document in all_results:
print(document)
# end-cursor-list

# start-cursor-close
results = collection.find()

...

await results.close()
# end-cursor-close
23 changes: 22 additions & 1 deletion source/includes/cursors/tailable-cursor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# start-tailable-cursor
oplog = client.local.oplog.rs
first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()
print(first)
Expand All @@ -13,4 +14,24 @@

# You end up here if the find() method returns no documents, or if
# no new documents are added to the collection for more than 1 second.
time.sleep(1)
time.sleep(1)
# end-tailable-cursor

# start-tailable-cursor-async
oplog = client.local.oplog.rs

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()
first = await oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()

first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()
print(first)
ts = first['ts']

while True:
cursor = oplog.find({'ts': {'$gt': ts}},
cursor_type=pymongo.CursorType.TAILABLE_AWAIT)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
await while async cursor.alive:
while cursor.alive:

await while async cursor.alive:
async for doc in cursor:
ts = doc['ts']
print(doc)

# You end up here if the find() method returns no documents, or if
# no new documents are added to the collection for more than 1 second.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
time.sleep(1)
await asyncio.sleep(1)

time.sleep(1)
# end-tailable-cursor-async
20 changes: 20 additions & 0 deletions source/includes/project/project-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# start-project-include
results = restaurants.find({ "name" : "Emerald Pub"}, {"name": 1, "cuisine": 1, "borough": 1})

async for restaurant in results:
print(restaurant)
# end-project-include

# start-project-include-without-id
results = restaurants.find({ "name" : "Emerald Pub"}, {"_id": 0, "name": 1, "cuisine": 1, "borough": 1})

async for restaurant in results:
print(restaurant)
# end-project-include-without-id

# start-project-exclude
results = restaurants.find({ "name" : "Emerald Pub"}, {"grades": 0, "address": 0} )

async for restaurant in results:
print(restaurant)
# end-project-exclude
38 changes: 38 additions & 0 deletions source/includes/read/change-streams-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# start-open-change-stream
database = client["sample_restaurants"]
collection = database["restaurants"]

async with await collection.watch() as stream:
async for change in stream:
print(change)
# end-open-change-stream

# start-update-for-change-stream
database = client["sample_restaurants"]
collection = database["restaurants"]

query_filter = { "name": "Blarney Castle" }
update_operation = { '$set' :
{ "cuisine": "Irish" }
}

result = await collection.update_one(query_filter, update_operation)
# end-update-for-change-stream

# start-change-stream-pipeline

change_pipeline = { "$match": { "operationType": "update" }},

async with await collection.watch(pipeline=change_pipeline) as stream:
async for change in stream:
print(change)
# end-change-stream-pipeline

# start-change-stream-post-image
database = client["sample_restaurants"]
collection = database["restaurants"]

async with await collection.watch(full_document='updateLookup') as stream:
async for change in stream:
print(change)
# end-change-stream-post-image
23 changes: 23 additions & 0 deletions source/includes/read/distinct-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# start-distinct
results = await restaurants.distinct("borough")

async for restaurant in results:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
async for restaurant in results:
for restaurant in results:

distinct() returns a list.

print(restaurant)
# end-distinct

# start-distinct-with-query
results = await restaurants.distinct("borough", {
"cuisine": "Italian"
})

async for restaurant in results:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
async for restaurant in results:
for restaurant in results:

print(restaurant)
# end-distinct-with-query

# start-distinct-with-comment
results = await restaurants.distinct("name",
{ "borough": "Bronx",
"cuisine": "Pizza" },
comment="Bronx pizza restaurants"
)
# end-distinct-with-comment
58 changes: 58 additions & 0 deletions source/includes/read/specify-documents-to-return-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# start-limit-method
results = restaurants.find({ "cuisine" : "Italian"}).limit(5)

async for restaurant in results:
print(restaurant["name"])
# end-limit-method

# start-limit-option
results = restaurants.find({ "cuisine" : "Italian"}, limit=5)

async for restaurant in results:
print(restaurant["name"])
# end-limit-option

# start-sort-method
results = restaurants.find({ "cuisine" : "Italian"}).sort("name", pymongo.ASCENDING)

async for restaurant in results:
print(restaurant["name"])
# end-sort-method

# start-sort-option
results = restaurants.find({ "cuisine" : "Italian"}, sort={"name": pymongo.ASCENDING} )

async for restaurant in results:
print(restaurant["name"])
# end-sort-option

# start-skip
results = restaurants.find({ "borough" : "Manhattan"}).skip(10)

async for restaurant in results:
print(restaurant["name"])
# end-skip

# start-skip-option
results = restaurants.find({ "borough" : "Manhattan"}, skip=10)

async for restaurant in results:
print(restaurant["name"])
# end-skip-option

# start-limit-sort-skip
results = restaurants.find({ "cuisine" : "Italian"}) \
.sort("name", pymongo.ASCENDING) \
.limit(5) \
.skip(10)

async for restaurant in results:
print(restaurant["name"])
# end-limit-sort-skip

# start-limit-sort-skip-option
results = restaurants.find({ "cuisine" : "Italian"}, limit=5, sort={"name": pymongo.ASCENDING}, skip=10)

async for restaurant in results:
print(restaurant["name"])
# end-limit-sort-skip-option
64 changes: 64 additions & 0 deletions source/includes/specify-query/specify-queries-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# start-sample-data
from pymongo import AsyncMongoClient

uri = "<connection string URI>"
client = AsyncMongoClient(uri)

try:
database = client["sample_fruit"]
collection = database["fruits"]

await collection.insert_many([
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "type": ["naval", "mandarin"] },
{ "_id": 4, "name": "pineapple", "qty": 3, "rating": 5, "color": "yellow" },
])

await client.close()

except Exception as e:
raise Exception("Error inserting documents: ", e)
# end-sample-data

# start-find-comparison
results = collection.find({ "rating": { "$gt" : 2 }})

async for f in results:
print(f)
# end-find-comparison

# start-find-logical
results = collection.find({
"$or": [
{ "qty": { "$gt": 5 }},
{ "color": "yellow" }
]
})

async for f in results:
print(f)
# end-find-logical

# start-find-array
results = collection.find({
"type" : { "$size": 2 }
})

async for f in results:
print(f)
# end-find-array

# start-find-element
results = collection.find( { "color" : { "$exists": "true" }} )

async for f in results:
print(f)
# end-find-element

# start-find-evaluation
results = collection.find({ "name" : { "$regex" : "p{2,}" }} )

async for f in results:
print(f)
# end-find-evaluation
39 changes: 39 additions & 0 deletions source/includes/usage-examples/retrieve-code-examples-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# start-find-one
results = await collection.find_one({ "<field name>" : "<value>" })

print(results)
# end-find-one
# start-find
results = collection.find({ "<field name>" : "<value>" })

async for document in results:
print(document)
# end-find
# start-count-all
count = await collection.count_documents({})

print(count)
#end-count-all
# start-count-query
count = await collection.count_documents({ "<field name>": "<value>" })

print(count)
# end-count-query

# start-estimated-count
count = await collection.estimated_document_count()

print(count)
# end-estimated-count
# start-distinct
results = collection.distinct("<field name>")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
results = collection.distinct("<field name>")
results = await collection.distinct("<field name>")


async for document in results:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
async for document in results:
for document in results:

print(document)
# end-distinct

# start-watch-for-changes
async with await collection.watch() as stream:
async for change in stream:
print(change)
# end-watch-for-changes
19 changes: 19 additions & 0 deletions source/includes/usage-examples/sample-app-async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import pymongo
from pymongo import AsyncMongoClient

try:
uri = "<connection string URI>"
client = AsyncMongoClient(uri)

database = client["<database name>"]
collection = database["<collection name>"]

# start example code here

# end example code here

client.close()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
client.close()
await client.close()

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Realize I forgot to wrap this in an async function (Python complains otherwise) so I can also do that


except Exception as e:
raise Exception(
"The following error occurred: ", e)
Loading
Loading