diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 994feb5d30..4043a473d9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -32,7 +32,7 @@ repos: name: ruff-format entry: uv run --group lint ruff format language: system - types_or: [python, pyi] + types_or: [python, pyi, markdown] require_serial: true - repo: local diff --git a/CODING-STANDARDS.md b/CODING-STANDARDS.md index ad73f15d36..66501fc0e6 100644 --- a/CODING-STANDARDS.md +++ b/CODING-STANDARDS.md @@ -156,7 +156,7 @@ if result == ... from pymongo import MongoClient if TYPE_CHECKING: - from pymongo.collection import Collection + from pymongo.collection import Collection ``` # Backwards compatibility diff --git a/README.md b/README.md index 8528bf35ac..211855e6bf 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,6 @@ ObjectId('4aba160ee23f6b543e000002') {'x': 10, '_id': ObjectId('4aba15ebe23f6b53b0000000')} >>> for item in db.my_collection.find(): ... print(item["x"]) -... 10 8 11 @@ -192,7 +191,6 @@ ObjectId('4aba160ee23f6b543e000002') 'x_1' >>> for item in db.my_collection.find().sort("x", pymongo.ASCENDING): ... print(item["x"]) -... 8 10 11 diff --git a/bson/decimal128.py b/bson/decimal128.py index 70dea15651..ba4832d528 100644 --- a/bson/decimal128.py +++ b/bson/decimal128.py @@ -69,7 +69,7 @@ class DecimalEncoder(TypeEncoder): For example:: opts = CodecOptions(type_registry=TypeRegistry([DecimalEncoder()])) - bson.encode({"d": decimal.Decimal('1.0')}, codec_options=opts) + bson.encode({"d": decimal.Decimal("1.0")}, codec_options=opts) .. versionadded:: 4.15 """ diff --git a/bson/raw_bson.py b/bson/raw_bson.py index 5d76fd8f04..f759ef4ef8 100644 --- a/bson/raw_bson.py +++ b/bson/raw_bson.py @@ -36,7 +36,6 @@ ... print(f"raw document: {doc.raw}") ... print(f"decoded document: {bson.decode(doc.raw)}") ... result = replica_db.test.insert_one(doc) - ... raw document: b'...' decoded document: {'_id': 1, 'a': 1} raw document: b'...' diff --git a/gridfs/asynchronous/grid_file.py b/gridfs/asynchronous/grid_file.py index 449b526b1e..748092ffd3 100644 --- a/gridfs/asynchronous/grid_file.py +++ b/gridfs/asynchronous/grid_file.py @@ -359,8 +359,7 @@ def find(self, *args: Any, **kwargs: Any) -> AsyncGridOutCursor: arbitrary queries on the files collection. Can be combined with other modifiers for additional control. For example:: - for grid_out in fs.find({"filename": "lisa.txt"}, - no_cursor_timeout=True): + for grid_out in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_out.read() would iterate through all versions of "lisa.txt" stored in GridFS. @@ -548,8 +547,8 @@ def open_upload_stream( my_db = MongoClient().test fs = GridFSBucket(my_db) with fs.open_upload_stream( - "test_file", chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) as grid_in: + "test_file", chunk_size_bytes=4, metadata={"contentType": "text/plain"} + ) as grid_in: grid_in.write("data I want to store!") # uploaded on close @@ -602,10 +601,8 @@ def open_upload_stream_with_id( my_db = MongoClient().test fs = GridFSBucket(my_db) with fs.open_upload_stream_with_id( - ObjectId(), - "test_file", - chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) as grid_in: + ObjectId(), "test_file", chunk_size_bytes=4, metadata={"contentType": "text/plain"} + ) as grid_in: grid_in.write("data I want to store!") # uploaded on close @@ -664,7 +661,8 @@ async def upload_from_stream( "test_file", "data I want to store!", chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) + metadata={"contentType": "text/plain"}, + ) Returns the _id of the uploaded file. @@ -716,7 +714,8 @@ async def upload_from_stream_with_id( "test_file", "data I want to store!", chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) + metadata={"contentType": "text/plain"}, + ) Raises :exc:`~gridfs.errors.NoFile` if no such version of that file exists. @@ -787,7 +786,7 @@ async def download_to_stream( # Get _id of file to read file_id = fs.upload_from_stream("test_file", "data I want to store!") # Get file to write to - file = open('myfile','wb+') + file = open("myfile", "wb+") fs.download_to_stream(file_id, file) file.seek(0) contents = file.read() @@ -877,8 +876,7 @@ def find(self, *args: Any, **kwargs: Any) -> AsyncGridOutCursor: For example:: - for grid_data in fs.find({"filename": "lisa.txt"}, - no_cursor_timeout=True): + for grid_data in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_data.read() would iterate through all versions of "lisa.txt" stored in GridFS. @@ -983,7 +981,7 @@ async def download_to_stream_by_name( my_db = MongoClient().test fs = GridFSBucket(my_db) # Get file to write to - file = open('myfile','wb') + file = open("myfile", "wb") fs.download_to_stream_by_name("test_file", file) Raises :exc:`~gridfs.errors.NoFile` if no such version of diff --git a/gridfs/synchronous/grid_file.py b/gridfs/synchronous/grid_file.py index 1e7ae35fb2..e3d57fb0af 100644 --- a/gridfs/synchronous/grid_file.py +++ b/gridfs/synchronous/grid_file.py @@ -357,8 +357,7 @@ def find(self, *args: Any, **kwargs: Any) -> GridOutCursor: arbitrary queries on the files collection. Can be combined with other modifiers for additional control. For example:: - for grid_out in fs.find({"filename": "lisa.txt"}, - no_cursor_timeout=True): + for grid_out in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_out.read() would iterate through all versions of "lisa.txt" stored in GridFS. @@ -546,8 +545,8 @@ def open_upload_stream( my_db = MongoClient().test fs = GridFSBucket(my_db) with fs.open_upload_stream( - "test_file", chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) as grid_in: + "test_file", chunk_size_bytes=4, metadata={"contentType": "text/plain"} + ) as grid_in: grid_in.write("data I want to store!") # uploaded on close @@ -600,10 +599,8 @@ def open_upload_stream_with_id( my_db = MongoClient().test fs = GridFSBucket(my_db) with fs.open_upload_stream_with_id( - ObjectId(), - "test_file", - chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) as grid_in: + ObjectId(), "test_file", chunk_size_bytes=4, metadata={"contentType": "text/plain"} + ) as grid_in: grid_in.write("data I want to store!") # uploaded on close @@ -662,7 +659,8 @@ def upload_from_stream( "test_file", "data I want to store!", chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) + metadata={"contentType": "text/plain"}, + ) Returns the _id of the uploaded file. @@ -712,7 +710,8 @@ def upload_from_stream_with_id( "test_file", "data I want to store!", chunk_size_bytes=4, - metadata={"contentType": "text/plain"}) + metadata={"contentType": "text/plain"}, + ) Raises :exc:`~gridfs.errors.NoFile` if no such version of that file exists. @@ -781,7 +780,7 @@ def download_to_stream( # Get _id of file to read file_id = fs.upload_from_stream("test_file", "data I want to store!") # Get file to write to - file = open('myfile','wb+') + file = open("myfile", "wb+") fs.download_to_stream(file_id, file) file.seek(0) contents = file.read() @@ -869,8 +868,7 @@ def find(self, *args: Any, **kwargs: Any) -> GridOutCursor: For example:: - for grid_data in fs.find({"filename": "lisa.txt"}, - no_cursor_timeout=True): + for grid_data in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_data.read() would iterate through all versions of "lisa.txt" stored in GridFS. @@ -975,7 +973,7 @@ def download_to_stream_by_name( my_db = MongoClient().test fs = GridFSBucket(my_db) # Get file to write to - file = open('myfile','wb') + file = open("myfile", "wb") fs.download_to_stream_by_name("test_file", file) Raises :exc:`~gridfs.errors.NoFile` if no such version of diff --git a/pymongo/__init__.py b/pymongo/__init__.py index 0b620a6cf2..7518a3f1f4 100644 --- a/pymongo/__init__.py +++ b/pymongo/__init__.py @@ -158,7 +158,7 @@ def timeout(seconds: float | None) -> AbstractContextManager[None]: with pymongo.timeout(5): coll.find_one() # Uses the 5 second deadline. with pymongo.timeout(3): - coll.find_one() # Uses the 3 second deadline. + coll.find_one() # Uses the 3 second deadline. coll.find_one() # Uses the original 5 second deadline. with pymongo.timeout(10): coll.find_one() # Still uses the original 5 second deadline. diff --git a/pymongo/asynchronous/change_stream.py b/pymongo/asynchronous/change_stream.py index e5253015bf..fc16add818 100644 --- a/pymongo/asynchronous/change_stream.py +++ b/pymongo/asynchronous/change_stream.py @@ -118,7 +118,7 @@ async def next(self) -> _DocumentType: try: resume_token = None - pipeline = [{'$match': {'operationType': 'insert'}}] + pipeline = [{"$match": {"operationType": "insert"}}] async with await db.collection.watch(pipeline) as stream: async for insert_change in stream: print(insert_change) @@ -129,13 +129,14 @@ async def next(self) -> _DocumentType: if resume_token is None: # There is no usable resume token because there was a # failure during AsyncChangeStream initialization. - logging.error('...') + logging.error("...") else: # Use the interrupted AsyncChangeStream's resume token to create # a new AsyncChangeStream. The new stream will continue from the # last seen insert change without missing any events. async with await db.collection.watch( - pipeline, resume_after=resume_token) as stream: + pipeline, resume_after=resume_token + ) as stream: async for insert_change in stream: print(insert_change) diff --git a/pymongo/asynchronous/client_session.py b/pymongo/asynchronous/client_session.py index 68180c5514..099e35f268 100644 --- a/pymongo/asynchronous/client_session.py +++ b/pymongo/asynchronous/client_session.py @@ -326,8 +326,10 @@ async def callback(session): orders = session.client.db.orders inventory = session.client.db.inventory await orders.insert_one({"sku": "abc123", "qty": 100}, session=session) - await inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}}, - {"$inc": {"qty": -100}}, session=session) + await inventory.update_one( + {"sku": "abc123", "qty": {"$gte": 100}}, {"$inc": {"qty": -100}}, session=session + ) + async with client.start_session() as session: await session.with_transaction(callback) diff --git a/pymongo/asynchronous/collection.py b/pymongo/asynchronous/collection.py index 618f253e4f..2f5ff04cb1 100644 --- a/pymongo/asynchronous/collection.py +++ b/pymongo/asynchronous/collection.py @@ -214,7 +214,7 @@ def __init__( names with leading underscores. You must use dict-style lookups instead:: - collection['__my_collection__'] + collection["__my_collection__"] Not: @@ -712,14 +712,15 @@ async def bulk_write( >>> async for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} >>> # DeleteMany, UpdateOne, and UpdateMany are also available. - ... >>> from pymongo import InsertOne, DeleteOne, ReplaceOne - >>> requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}), - ... ReplaceOne({'w': 1}, {'z': 1}, upsert=True)] + >>> requests = [ + ... InsertOne({"y": 1}), + ... DeleteOne({"x": 1}), + ... ReplaceOne({"w": 1}, {"z": 1}, upsert=True), + ... ] >>> result = await db.test.bulk_write(requests) >>> result.inserted_count 1 @@ -731,7 +732,6 @@ async def bulk_write( {2: ObjectId('54f62ee28891e756a6e1abd5')} >>> async for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')} @@ -840,12 +840,12 @@ async def insert_one( ) -> InsertOneResult: """Insert a single document. - >>> await db.test.count_documents({'x': 1}) + >>> await db.test.count_documents({"x": 1}) 0 - >>> result = await db.test.insert_one({'x': 1}) + >>> result = await db.test.insert_one({"x": 1}) >>> result.inserted_id ObjectId('54f112defba522406c9cc208') - >>> await db.test.find_one({'x': 1}) + >>> await db.test.find_one({"x": 1}) {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')} :param document: The document to insert. Must be a mutable mapping @@ -908,7 +908,7 @@ async def insert_many( >>> await db.test.count_documents({}) 0 - >>> result = await db.test.insert_many([{'x': i} for i in range(2)]) + >>> result = await db.test.insert_many([{"x": i} for i in range(2)]) >>> await result.inserted_ids [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')] >>> await db.test.count_documents({}) @@ -1131,29 +1131,27 @@ async def replace_one( >>> async for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')} - >>> result = await db.test.replace_one({'x': 1}, {'y': 1}) + >>> result = await db.test.replace_one({"x": 1}, {"y": 1}) >>> result.matched_count 1 >>> result.modified_count 1 >>> async for doc in db.test.find({}): ... print(doc) - ... {'y': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')} The *upsert* option can be used to insert a new document if a matching document does not exist. - >>> result = await db.test.replace_one({'x': 1}, {'x': 1}, True) + >>> result = await db.test.replace_one({"x": 1}, {"x": 1}, True) >>> result.matched_count 0 >>> result.modified_count 0 >>> result.upserted_id ObjectId('54f11e5c8891e756a6e1abd4') - >>> await db.test.find_one({'x': 1}) + >>> await db.test.find_one({"x": 1}) {'x': 1, '_id': ObjectId('54f11e5c8891e756a6e1abd4')} :param filter: A query that matches the document to replace. @@ -1240,18 +1238,16 @@ async def update_one( >>> async for doc in db.test.find(): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> result = await db.test.update_one({'x': 1}, {'$inc': {'x': 3}}) + >>> result = await db.test.update_one({"x": 1}, {"$inc": {"x": 3}}) >>> result.matched_count 1 >>> result.modified_count 1 >>> async for doc in db.test.find(): ... print(doc) - ... {'x': 4, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} @@ -1259,7 +1255,7 @@ async def update_one( If ``upsert=True`` and no documents match the filter, create a new document based on the filter criteria and update modifications. - >>> result = await db.test.update_one({'x': -10}, {'$inc': {'x': 3}}, upsert=True) + >>> result = await db.test.update_one({"x": -10}, {"$inc": {"x": 3}}, upsert=True) >>> result.matched_count 0 >>> result.modified_count @@ -1358,18 +1354,16 @@ async def update_many( >>> async for doc in db.test.find(): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> result = await db.test.update_many({'x': 1}, {'$inc': {'x': 3}}) + >>> result = await db.test.update_many({"x": 1}, {"$inc": {"x": 3}}) >>> result.matched_count 3 >>> result.modified_count 3 >>> async for doc in db.test.find(): ... print(doc) - ... {'x': 4, '_id': 0} {'x': 4, '_id': 1} {'x': 4, '_id': 2} @@ -1587,12 +1581,12 @@ async def delete_one( ) -> DeleteResult: """Delete a single document matching the filter. - >>> await db.test.count_documents({'x': 1}) + >>> await db.test.count_documents({"x": 1}) 3 - >>> result = await db.test.delete_one({'x': 1}) + >>> result = await db.test.delete_one({"x": 1}) >>> result.deleted_count 1 - >>> await db.test.count_documents({'x': 1}) + >>> await db.test.count_documents({"x": 1}) 2 :param filter: A query that matches the document to delete. @@ -1652,12 +1646,12 @@ async def delete_many( ) -> DeleteResult: """Delete one or more documents matching the filter. - >>> await db.test.count_documents({'x': 1}) + >>> await db.test.count_documents({"x": 1}) 3 - >>> result = await db.test.delete_many({'x': 1}) + >>> result = await db.test.delete_many({"x": 1}) >>> result.deleted_count 3 - >>> await db.test.count_documents({'x': 1}) + >>> await db.test.count_documents({"x": 1}) 0 :param filter: A query that matches the documents to delete. @@ -2190,8 +2184,7 @@ async def create_indexes( """Create one or more indexes on this collection. >>> from pymongo import IndexModel, ASCENDING, DESCENDING - >>> index1 = IndexModel([("hello", DESCENDING), - ... ("world", ASCENDING)], name="hello_world") + >>> index1 = IndexModel([("hello", DESCENDING), ("world", ASCENDING)], name="hello_world") >>> index2 = IndexModel([("goodbye", DESCENDING)]) >>> await db.test.create_indexes([index1, index2]) ["hello_world", "goodbye_-1"] @@ -2513,7 +2506,6 @@ async def list_indexes( >>> async for index in await db.test.list_indexes(): ... print(index) - ... SON([('v', 2), ('key', SON([('_id', 1)])), ('name', '_id_')]) Cursors are closed automatically when they are exhausted (the last batch of data is @@ -3073,8 +3065,9 @@ async def aggregate_raw_batches( :mod:`bson` module. >>> import bson - >>> cursor = await db.test.aggregate_raw_batches([ - ... {'$project': {'x': {'$multiply': [2, '$x']}}}]) + >>> cursor = await db.test.aggregate_raw_batches( + ... [{"$project": {"x": {"$multiply": [2, "$x"]}}}] + ... ) >>> async for batch in cursor: ... print(bson.decode_all(batch)) @@ -3341,32 +3334,30 @@ async def find_one_and_delete( ) -> _DocumentType | None: """Find a single document and delete it, returning the document. - >>> await db.test.count_documents({'x': 1}) + >>> await db.test.count_documents({"x": 1}) 2 - >>> await db.test.find_one_and_delete({'x': 1}) + >>> await db.test.find_one_and_delete({"x": 1}) {'x': 1, '_id': ObjectId('54f4e12bfba5220aa4d6dee8')} - >>> await db.test.count_documents({'x': 1}) + >>> await db.test.count_documents({"x": 1}) 1 Returns ``None`` if no document matches the filter. - >>> await db.test.find_one_and_delete({'_exists': False}) + >>> await db.test.find_one_and_delete({"_exists": False}) If multiple documents match *filter*, a *sort* can be applied. - >>> async for doc in db.test.find({'x': 1}): + >>> async for doc in db.test.find({"x": 1}): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> await db.test.find_one_and_delete( - ... {'x': 1}, sort=[('_id', pymongo.DESCENDING)]) + >>> await db.test.find_one_and_delete({"x": 1}, sort=[("_id", pymongo.DESCENDING)]) {'x': 1, '_id': 2} The *projection* option can be used to limit the fields returned. - >>> await db.test.find_one_and_delete({'x': 1}, projection={'_id': False}) + >>> await db.test.find_one_and_delete({"x": 1}, projection={"_id": False}) {'x': 1} :param filter: A query that matches the document to delete. @@ -3439,17 +3430,17 @@ async def find_one_and_replace( Return either the original or the replaced document. - >>> await db.test.find_one({'x': 1}) + >>> await db.test.find_one({"x": 1}) {'_id': 0, 'x': 1} - >>> await db.test.find_one_and_replace({'x': 1}, {'y': 2}) + >>> await db.test.find_one_and_replace({"x": 1}, {"y": 2}) {'_id': 0, 'x': 1} - >>> await db.test.find_one({'x': 1}) - >>> await db.test.find_one({'y': 2}) + >>> await db.test.find_one({"x": 1}) + >>> await db.test.find_one({"y": 2}) {'_id': 0, 'y': 2} Returns ``None`` if no document matches the filter. - >>> await db.test.find_one_and_replace({'_exists': False}, {'x': 1}) + >>> await db.test.find_one_and_replace({"_exists": False}, {"x": 1}) The :meth:`find_one_and_replace` method differs from :meth:`find_one_and_update` by replacing the document matched by @@ -3457,15 +3448,13 @@ async def find_one_and_replace( >>> async for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> await db.test.find_one_and_replace({'x': 1}, {'y': 1}) + >>> await db.test.find_one_and_replace({"x": 1}, {"y": 1}) {'x': 1, '_id': 0} >>> async for doc in db.test.find({}): ... print(doc) - ... {'y': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} @@ -3560,18 +3549,18 @@ async def find_one_and_update( Return either the original or the updated document. - >>> await db.test.find_one({'_id': 665}) + >>> await db.test.find_one({"_id": 665}) {'_id': 665, 'done': False, 'count': 25} >>> await db.test.find_one_and_update( - ... {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}}) + ... {"_id": 665}, {"$inc": {"count": 1}, "$set": {"done": True}} + ... ) {'_id': 665, 'done': False, 'count': 25} - >>> await db.test.find_one({'_id': 665}) + >>> await db.test.find_one({"_id": 665}) {'_id': 665, 'done': True, 'count': 26} Returns ``None`` if no document matches the filter. - >>> await db.test.find_one_and_update( - ... {'_exists': False}, {'$inc': {'count': 1}}) + >>> await db.test.find_one_and_update({"_exists": False}, {"$inc": {"count": 1}}) When the filter matches, by default :meth:`find_one_and_update` returns the original version of the document before the update was @@ -3581,18 +3570,18 @@ async def find_one_and_update( >>> from pymongo import ReturnDocument >>> await db.example.find_one_and_update( - ... {'_id': 'userid'}, - ... {'$inc': {'seq': 1}}, - ... return_document=ReturnDocument.AFTER) + ... {"_id": "userid"}, {"$inc": {"seq": 1}}, return_document=ReturnDocument.AFTER + ... ) {'_id': 'userid', 'seq': 1} You can limit the fields returned with the *projection* option. >>> await db.example.find_one_and_update( - ... {'_id': 'userid'}, - ... {'$inc': {'seq': 1}}, - ... projection={'seq': True, '_id': False}, - ... return_document=ReturnDocument.AFTER) + ... {"_id": "userid"}, + ... {"$inc": {"seq": 1}}, + ... projection={"seq": True, "_id": False}, + ... return_document=ReturnDocument.AFTER, + ... ) {'seq': 2} The *upsert* option can be used to create the document if it doesn't @@ -3601,24 +3590,23 @@ async def find_one_and_update( >>> (await db.example.delete_many({})).deleted_count 1 >>> await db.example.find_one_and_update( - ... {'_id': 'userid'}, - ... {'$inc': {'seq': 1}}, - ... projection={'seq': True, '_id': False}, + ... {"_id": "userid"}, + ... {"$inc": {"seq": 1}}, + ... projection={"seq": True, "_id": False}, ... upsert=True, - ... return_document=ReturnDocument.AFTER) + ... return_document=ReturnDocument.AFTER, + ... ) {'seq': 1} If multiple documents match *filter*, a *sort* can be applied. - >>> async for doc in db.test.find({'done': True}): + >>> async for doc in db.test.find({"done": True}): ... print(doc) - ... {'_id': 665, 'done': True, 'result': {'count': 26}} {'_id': 701, 'done': True, 'result': {'count': 17}} >>> await db.test.find_one_and_update( - ... {'done': True}, - ... {'$set': {'final': True}}, - ... sort=[('_id', pymongo.DESCENDING)]) + ... {"done": True}, {"$set": {"final": True}}, sort=[("_id", pymongo.DESCENDING)] + ... ) {'_id': 701, 'done': True, 'result': {'count': 17}} :param filter: A query that matches the document to update. diff --git a/pymongo/asynchronous/database.py b/pymongo/asynchronous/database.py index a33c00fb77..9861f5e72c 100644 --- a/pymongo/asynchronous/database.py +++ b/pymongo/asynchronous/database.py @@ -104,7 +104,7 @@ def __init__( of :class:`~pymongo.asynchronous.collection.AsyncCollection` for attribute names with leading underscores. You must use dict-style lookups instead:: - db['__my_collection__'] + db["__my_collection__"] Not: @@ -174,7 +174,7 @@ def with_options( >>> db1.read_preference Primary() >>> from pymongo.read_preferences import Secondary - >>> db2 = db1.with_options(read_preference=Secondary([{'node': 'analytics'}])) + >>> db2 = db1.with_options(read_preference=Secondary([{"node": "analytics"}])) >>> db1.read_preference Primary() >>> db2.read_preference @@ -265,8 +265,7 @@ def get_collection( >>> coll1.read_preference Primary() >>> from pymongo import ReadPreference - >>> coll2 = db.get_collection( - ... 'test', read_preference=ReadPreference.SECONDARY) + >>> coll2 = db.get_collection("test", read_preference=ReadPreference.SECONDARY) >>> coll2.read_preference Secondary(tag_sets=None) @@ -1295,22 +1294,21 @@ async def drop_collection( Queryable Encryption. For example:: { - "escCollection": "enxcol_.encryptedCollection.esc", - "ecocCollection": "enxcol_.encryptedCollection.ecoc", - "fields": [ - { - "path": "firstName", - "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')), - "bsonType": "string", - "queries": {"queryType": "equality"} - }, - { - "path": "ssn", - "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')), - "bsonType": "string" - } - ] - + "escCollection": "enxcol_.encryptedCollection.esc", + "ecocCollection": "enxcol_.encryptedCollection.ecoc", + "fields": [ + { + "path": "firstName", + "keyId": Binary.from_uuid(UUID("00000000-0000-0000-0000-000000000000")), + "bsonType": "string", + "queries": {"queryType": "equality"}, + }, + { + "path": "ssn", + "keyId": Binary.from_uuid(UUID("04104104-1041-0410-4104-104104104104")), + "bsonType": "string", + }, + ], } diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index f8c4a07d6e..f9d084397d 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -543,7 +543,7 @@ def __init__( :class:`pymongo.mongo_client.AsyncMongoClient`. For example, to override the system default CA file:: - kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}} + kms_tls_options = {"kmip": {"tlsCAFile": certifi.where()}} Or to supply a client certificate:: diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index 7e1b784a9d..aba2e7f702 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -222,20 +222,22 @@ def __init__( from urllib.parse import quote_plus - uri = "mongodb://%s:%s@%s" % ( - quote_plus(user), quote_plus(password), host) + uri = "mongodb://%s:%s@%s" % (quote_plus(user), quote_plus(password), host) client = AsyncMongoClient(uri) Unix domain sockets are also supported. The socket path must be percent encoded in the URI:: uri = "mongodb://%s:%s@%s" % ( - quote_plus(user), quote_plus(password), quote_plus(socket_path)) + quote_plus(user), + quote_plus(password), + quote_plus(socket_path), + ) client = AsyncMongoClient(uri) But not when passed as a simple hostname:: - client = AsyncMongoClient('/tmp/mongodb-27017.sock') + client = AsyncMongoClient("/tmp/mongodb-27017.sock") Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The URI must include one, and only one, hostname. The hostname will be @@ -265,10 +267,11 @@ def __init__( like this:: from pymongo.errors import ConnectionFailure + client = AsyncMongoClient() try: # The ping command is cheap and does not require auth. - client.admin.command('ping') + client.admin.command("ping") except ConnectionFailure: print("Server not available") @@ -502,6 +505,7 @@ def __init__( def validator(host: str) -> bool: return host.endswith((".a.example.com", ".b.example.com")) + AsyncMongoClient( "mongodb+srv://cluster.example.com/", srv_host_validator=validator, @@ -791,7 +795,7 @@ def validator(host: str) -> bool: In PyMongo 2.x, :class:`~pymongo.asynchronous.AsyncMongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: - AsyncMongoClient(['host1.com:27017', 'host2.com:27017']) + AsyncMongoClient(["host1.com:27017", "host2.com:27017"]) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or @@ -825,7 +829,7 @@ def validator(host: str) -> bool: instance of :class:`~pymongo.asynchronous.database.AsyncDatabase` for attribute names with leading underscores. You must use dict-style lookups instead:: - client['__my_database__'] + client["__my_database__"] Not:: @@ -1591,12 +1595,12 @@ def get_default_database( ) -> database.AsyncDatabase[_DocumentType]: """Get the database named in the MongoDB connection URI. - >>> uri = 'mongodb://host/my_database' + >>> uri = "mongodb://host/my_database" >>> client = AsyncMongoClient(uri) >>> db = client.get_default_database() - >>> assert db.name == 'my_database' + >>> assert db.name == "my_database" >>> db = client.get_database() - >>> assert db.name == 'my_database' + >>> assert db.name == "my_database" Useful in scripts where you want to choose which database to use based only on the URI in a configuration file. @@ -1661,8 +1665,7 @@ def get_database( >>> db1.read_preference Primary() >>> from pymongo import ReadPreference - >>> db2 = client.get_database( - ... 'test', read_preference=ReadPreference.SECONDARY) + >>> db2 = client.get_database("test", read_preference=ReadPreference.SECONDARY) >>> db2.read_preference Secondary(tag_sets=None) @@ -2587,22 +2590,23 @@ async def bulk_write( >>> async for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} ... >>> async for doc in db.coll.find({}): ... print(doc) - ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} ... >>> # DeleteMany, UpdateOne, and UpdateMany are also available. >>> from pymongo import InsertOne, DeleteOne, ReplaceOne - >>> models = [InsertOne(namespace="db.test", document={'y': 1}), - ... DeleteOne(namespace="db.test", filter={'x': 1}), - ... InsertOne(namespace="db.coll", document={'y': 2}), - ... ReplaceOne(namespace="db.test", filter={'w': 1}, - ... replacement={'z': 1}, upsert=True)] + >>> models = [ + ... InsertOne(namespace="db.test", document={"y": 1}), + ... DeleteOne(namespace="db.test", filter={"x": 1}), + ... InsertOne(namespace="db.coll", document={"y": 2}), + ... ReplaceOne( + ... namespace="db.test", filter={"w": 1}, replacement={"z": 1}, upsert=True + ... ), + ... ] >>> result = await client.bulk_write(models=models) >>> result.inserted_count 2 @@ -2614,14 +2618,12 @@ async def bulk_write( 1 >>> async for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')} ... >>> async for doc in db.coll.find({}): ... print(doc) - ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} {'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')} diff --git a/pymongo/cursor_shared.py b/pymongo/cursor_shared.py index fcbb416f78..71527a1c4f 100644 --- a/pymongo/cursor_shared.py +++ b/pymongo/cursor_shared.py @@ -868,36 +868,32 @@ def sort(self, key_or_list: _Hint, direction: int | str | None = None) -> Self: :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`.:: # Synchronous - for doc in collection.find().sort('field', pymongo.ASCENDING): + for doc in collection.find().sort("field", pymongo.ASCENDING): print(doc) # Asynchronous - async for doc in collection.find().sort('field', pymongo.ASCENDING): + async for doc in collection.find().sort("field", pymongo.ASCENDING): print(doc) To sort by multiple fields, pass a list of (key, direction) pairs. If just a name is given, :data:`~pymongo.ASCENDING` will be inferred:: # Synchronous - for doc in collection.find().sort([ - 'field1', - ('field2', pymongo.DESCENDING)]): + for doc in collection.find().sort(["field1", ("field2", pymongo.DESCENDING)]): print(doc) # Asynchronous - async for doc in collection.find().sort([ - 'field1', - ('field2', pymongo.DESCENDING)]): + async for doc in collection.find().sort(["field1", ("field2", pymongo.DESCENDING)]): print(doc) Text search results can be sorted by relevance:: cursor = db.test.find( - {'$text': {'$search': 'some words'}}, - {'score': {'$meta': 'textScore'}}) + {"$text": {"$search": "some words"}}, {"score": {"$meta": "textScore"}} + ) # Sort by 'score' field. - cursor.sort([('score', {'$meta': 'textScore'})]) + cursor.sort([("score", {"$meta": "textScore"})]) # Synchronous for doc in cursor: @@ -983,11 +979,11 @@ def where(self, code: str | Code) -> Self: # Find all documents where field "a" is less than "b" plus "c". # Synchronous - for doc in db.test.find().where('this.a < (this.b + this.c)'): + for doc in db.test.find().where("this.a < (this.b + this.c)"): print(doc) # Asynchronous - async for doc in db.test.find().where('this.a < (this.b + this.c)'): + async for doc in db.test.find().where("this.a < (this.b + this.c)"): print(doc) Raises :class:`TypeError` if `code` is not an instance of diff --git a/pymongo/encryption_options.py b/pymongo/encryption_options.py index f867c01716..980a319158 100644 --- a/pymongo/encryption_options.py +++ b/pymongo/encryption_options.py @@ -135,8 +135,8 @@ def __init__( For example, to configure multiple local KMS providers:: kms_providers = { - "local": {"key": local_kek1}, # Unnamed KMS provider. - "local:myname": {"key": local_kek2}, # Named KMS provider with name "myname". + "local": {"key": local_kek1}, # Unnamed KMS provider. + "local:myname": {"key": local_kek2}, # Named KMS provider with name "myname". } :param key_vault_namespace: The namespace for the key vault collection. @@ -187,7 +187,7 @@ def __init__( :class:`pymongo.mongo_client.MongoClient`. For example, to override the system default CA file:: - kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}} + kms_tls_options = {"kmip": {"tlsCAFile": certifi.where()}} Or to supply a client certificate:: diff --git a/pymongo/monitoring.py b/pymongo/monitoring.py index 0b2e76c4ef..59c02245f6 100644 --- a/pymongo/monitoring.py +++ b/pymongo/monitoring.py @@ -33,34 +33,41 @@ from pymongo import monitoring - class CommandLogger(monitoring.CommandListener): + class CommandLogger(monitoring.CommandListener): def started(self, event): - logging.info("Command {0.command_name} with request id " - "{0.request_id} started on server " - "{0.connection_id}".format(event)) + logging.info( + "Command {0.command_name} with request id " + "{0.request_id} started on server " + "{0.connection_id}".format(event) + ) def succeeded(self, event): - logging.info("Command {0.command_name} with request id " - "{0.request_id} on server {0.connection_id} " - "succeeded in {0.duration_micros} " - "microseconds".format(event)) + logging.info( + "Command {0.command_name} with request id " + "{0.request_id} on server {0.connection_id} " + "succeeded in {0.duration_micros} " + "microseconds".format(event) + ) def failed(self, event): - logging.info("Command {0.command_name} with request id " - "{0.request_id} on server {0.connection_id} " - "failed in {0.duration_micros} " - "microseconds".format(event)) + logging.info( + "Command {0.command_name} with request id " + "{0.request_id} on server {0.connection_id} " + "failed in {0.duration_micros} " + "microseconds".format(event) + ) + monitoring.register(CommandLogger()) Server discovery and monitoring events are also available. For example:: class ServerLogger(monitoring.ServerListener): - def opened(self, event): - logging.info("Server {0.server_address} added to topology " - "{0.topology_id}".format(event)) + logging.info( + "Server {0.server_address} added to topology {0.topology_id}".format(event) + ) def description_changed(self, event): previous_server_type = event.previous_description.server_type @@ -70,38 +77,41 @@ def description_changed(self, event): logging.info( "Server {0.server_address} changed type from " "{0.previous_description.server_type_name} to " - "{0.new_description.server_type_name}".format(event)) + "{0.new_description.server_type_name}".format(event) + ) def closed(self, event): - logging.warning("Server {0.server_address} removed from topology " - "{0.topology_id}".format(event)) + logging.warning( + "Server {0.server_address} removed from topology {0.topology_id}".format(event) + ) class HeartbeatLogger(monitoring.ServerHeartbeatListener): - def started(self, event): - logging.info("Heartbeat sent to server " - "{0.connection_id}".format(event)) + logging.info("Heartbeat sent to server {0.connection_id}".format(event)) def succeeded(self, event): # The reply.document attribute was added in PyMongo 3.4. - logging.info("Heartbeat to server {0.connection_id} " - "succeeded with reply " - "{0.reply.document}".format(event)) + logging.info( + "Heartbeat to server {0.connection_id} " + "succeeded with reply " + "{0.reply.document}".format(event) + ) def failed(self, event): - logging.warning("Heartbeat to server {0.connection_id} " - "failed with error {0.reply}".format(event)) + logging.warning( + "Heartbeat to server {0.connection_id} failed with error {0.reply}".format(event) + ) - class TopologyLogger(monitoring.TopologyListener): + class TopologyLogger(monitoring.TopologyListener): def opened(self, event): - logging.info("Topology with id {0.topology_id} " - "opened".format(event)) + logging.info("Topology with id {0.topology_id} opened".format(event)) def description_changed(self, event): - logging.info("Topology description updated for " - "topology id {0.topology_id}".format(event)) + logging.info( + "Topology description updated for topology id {0.topology_id}".format(event) + ) previous_topology_type = event.previous_description.topology_type new_topology_type = event.new_description.topology_type if new_topology_type != previous_topology_type: @@ -109,7 +119,8 @@ def description_changed(self, event): logging.info( "Topology {0.topology_id} changed type from " "{0.previous_description.topology_type_name} to " - "{0.new_description.topology_type_name}".format(event)) + "{0.new_description.topology_type_name}".format(event) + ) # The has_writable_server and has_readable_server methods # were added in PyMongo 3.4. if not event.new_description.has_writable_server(): @@ -118,13 +129,11 @@ def description_changed(self, event): logging.warning("No readable servers available.") def closed(self, event): - logging.info("Topology with id {0.topology_id} " - "closed".format(event)) + logging.info("Topology with id {0.topology_id} closed".format(event)) Connection monitoring and pooling events are also available. For example:: class ConnectionPoolLogger(ConnectionPoolListener): - def pool_created(self, event): logging.info("[pool {0.address}] pool created".format(event)) @@ -138,33 +147,42 @@ def pool_closed(self, event): logging.info("[pool {0.address}] pool closed".format(event)) def connection_created(self, event): - logging.info("[pool {0.address}][connection #{0.connection_id}] " - "connection created".format(event)) + logging.info( + "[pool {0.address}][connection #{0.connection_id}] connection created".format(event) + ) def connection_ready(self, event): - logging.info("[pool {0.address}][connection #{0.connection_id}] " - "connection setup succeeded".format(event)) + logging.info( + "[pool {0.address}][connection #{0.connection_id}] " + "connection setup succeeded".format(event) + ) def connection_closed(self, event): - logging.info("[pool {0.address}][connection #{0.connection_id}] " - "connection closed, reason: " - "{0.reason}".format(event)) + logging.info( + "[pool {0.address}][connection #{0.connection_id}] " + "connection closed, reason: " + "{0.reason}".format(event) + ) def connection_check_out_started(self, event): - logging.info("[pool {0.address}] connection check out " - "started".format(event)) + logging.info("[pool {0.address}] connection check out started".format(event)) def connection_check_out_failed(self, event): - logging.info("[pool {0.address}] connection check out " - "failed, reason: {0.reason}".format(event)) + logging.info( + "[pool {0.address}] connection check out failed, reason: {0.reason}".format(event) + ) def connection_checked_out(self, event): - logging.info("[pool {0.address}][connection #{0.connection_id}] " - "connection checked out of pool".format(event)) + logging.info( + "[pool {0.address}][connection #{0.connection_id}] " + "connection checked out of pool".format(event) + ) def connection_checked_in(self, event): - logging.info("[pool {0.address}][connection #{0.connection_id}] " - "connection checked into pool".format(event)) + logging.info( + "[pool {0.address}][connection #{0.connection_id}] " + "connection checked into pool".format(event) + ) Event listeners can also be registered per instance of diff --git a/pymongo/read_preferences.py b/pymongo/read_preferences.py index 7768523be4..d07064cab7 100644 --- a/pymongo/read_preferences.py +++ b/pymongo/read_preferences.py @@ -173,7 +173,7 @@ def tag_sets(self) -> _TagSets: For example, to only send a query to an analytic node:: - Nearest(tag_sets=[{"node":"analytics"}]) + Nearest(tag_sets=[{"node": "analytics"}]) Or using :class:`SecondaryPreferred`:: @@ -563,7 +563,7 @@ class ReadPreference: Apps can also create a custom read preference, for example:: - Nearest(tag_sets=[{"node":"analytics"}]) + Nearest(tag_sets=[{"node": "analytics"}]) See `Read and Write Settings `_ diff --git a/pymongo/synchronous/change_stream.py b/pymongo/synchronous/change_stream.py index 564b67f57f..9ade3de090 100644 --- a/pymongo/synchronous/change_stream.py +++ b/pymongo/synchronous/change_stream.py @@ -118,7 +118,7 @@ def next(self) -> _DocumentType: try: resume_token = None - pipeline = [{'$match': {'operationType': 'insert'}}] + pipeline = [{"$match": {"operationType": "insert"}}] with db.collection.watch(pipeline) as stream: for insert_change in stream: print(insert_change) @@ -129,13 +129,12 @@ def next(self) -> _DocumentType: if resume_token is None: # There is no usable resume token because there was a # failure during ChangeStream initialization. - logging.error('...') + logging.error("...") else: # Use the interrupted ChangeStream's resume token to create # a new ChangeStream. The new stream will continue from the # last seen insert change without missing any events. - with db.collection.watch( - pipeline, resume_after=resume_token) as stream: + with db.collection.watch(pipeline, resume_after=resume_token) as stream: for insert_change in stream: print(insert_change) diff --git a/pymongo/synchronous/client_session.py b/pymongo/synchronous/client_session.py index fd24dbf230..a2c70a0285 100644 --- a/pymongo/synchronous/client_session.py +++ b/pymongo/synchronous/client_session.py @@ -323,8 +323,10 @@ def callback(session): orders = session.client.db.orders inventory = session.client.db.inventory orders.insert_one({"sku": "abc123", "qty": 100}, session=session) - inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}}, - {"$inc": {"qty": -100}}, session=session) + inventory.update_one( + {"sku": "abc123", "qty": {"$gte": 100}}, {"$inc": {"qty": -100}}, session=session + ) + with client.start_session() as session: session.with_transaction(callback) diff --git a/pymongo/synchronous/collection.py b/pymongo/synchronous/collection.py index 42392b5a87..2a21874b48 100644 --- a/pymongo/synchronous/collection.py +++ b/pymongo/synchronous/collection.py @@ -217,7 +217,7 @@ def __init__( names with leading underscores. You must use dict-style lookups instead:: - collection['__my_collection__'] + collection["__my_collection__"] Not: @@ -709,14 +709,15 @@ def bulk_write( >>> for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} >>> # DeleteMany, UpdateOne, and UpdateMany are also available. - ... >>> from pymongo import InsertOne, DeleteOne, ReplaceOne - >>> requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}), - ... ReplaceOne({'w': 1}, {'z': 1}, upsert=True)] + >>> requests = [ + ... InsertOne({"y": 1}), + ... DeleteOne({"x": 1}), + ... ReplaceOne({"w": 1}, {"z": 1}, upsert=True), + ... ] >>> result = db.test.bulk_write(requests) >>> result.inserted_count 1 @@ -728,7 +729,6 @@ def bulk_write( {2: ObjectId('54f62ee28891e756a6e1abd5')} >>> for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')} @@ -837,12 +837,12 @@ def insert_one( ) -> InsertOneResult: """Insert a single document. - >>> db.test.count_documents({'x': 1}) + >>> db.test.count_documents({"x": 1}) 0 - >>> result = db.test.insert_one({'x': 1}) + >>> result = db.test.insert_one({"x": 1}) >>> result.inserted_id ObjectId('54f112defba522406c9cc208') - >>> db.test.find_one({'x': 1}) + >>> db.test.find_one({"x": 1}) {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')} :param document: The document to insert. Must be a mutable mapping @@ -905,7 +905,7 @@ def insert_many( >>> db.test.count_documents({}) 0 - >>> result = db.test.insert_many([{'x': i} for i in range(2)]) + >>> result = db.test.insert_many([{"x": i} for i in range(2)]) >>> result.inserted_ids [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')] >>> db.test.count_documents({}) @@ -1128,29 +1128,27 @@ def replace_one( >>> for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')} - >>> result = db.test.replace_one({'x': 1}, {'y': 1}) + >>> result = db.test.replace_one({"x": 1}, {"y": 1}) >>> result.matched_count 1 >>> result.modified_count 1 >>> for doc in db.test.find({}): ... print(doc) - ... {'y': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')} The *upsert* option can be used to insert a new document if a matching document does not exist. - >>> result = db.test.replace_one({'x': 1}, {'x': 1}, True) + >>> result = db.test.replace_one({"x": 1}, {"x": 1}, True) >>> result.matched_count 0 >>> result.modified_count 0 >>> result.upserted_id ObjectId('54f11e5c8891e756a6e1abd4') - >>> db.test.find_one({'x': 1}) + >>> db.test.find_one({"x": 1}) {'x': 1, '_id': ObjectId('54f11e5c8891e756a6e1abd4')} :param filter: A query that matches the document to replace. @@ -1237,18 +1235,16 @@ def update_one( >>> for doc in db.test.find(): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> result = db.test.update_one({'x': 1}, {'$inc': {'x': 3}}) + >>> result = db.test.update_one({"x": 1}, {"$inc": {"x": 3}}) >>> result.matched_count 1 >>> result.modified_count 1 >>> for doc in db.test.find(): ... print(doc) - ... {'x': 4, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} @@ -1256,7 +1252,7 @@ def update_one( If ``upsert=True`` and no documents match the filter, create a new document based on the filter criteria and update modifications. - >>> result = db.test.update_one({'x': -10}, {'$inc': {'x': 3}}, upsert=True) + >>> result = db.test.update_one({"x": -10}, {"$inc": {"x": 3}}, upsert=True) >>> result.matched_count 0 >>> result.modified_count @@ -1355,18 +1351,16 @@ def update_many( >>> for doc in db.test.find(): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> result = db.test.update_many({'x': 1}, {'$inc': {'x': 3}}) + >>> result = db.test.update_many({"x": 1}, {"$inc": {"x": 3}}) >>> result.matched_count 3 >>> result.modified_count 3 >>> for doc in db.test.find(): ... print(doc) - ... {'x': 4, '_id': 0} {'x': 4, '_id': 1} {'x': 4, '_id': 2} @@ -1584,12 +1578,12 @@ def delete_one( ) -> DeleteResult: """Delete a single document matching the filter. - >>> db.test.count_documents({'x': 1}) + >>> db.test.count_documents({"x": 1}) 3 - >>> result = db.test.delete_one({'x': 1}) + >>> result = db.test.delete_one({"x": 1}) >>> result.deleted_count 1 - >>> db.test.count_documents({'x': 1}) + >>> db.test.count_documents({"x": 1}) 2 :param filter: A query that matches the document to delete. @@ -1649,12 +1643,12 @@ def delete_many( ) -> DeleteResult: """Delete one or more documents matching the filter. - >>> db.test.count_documents({'x': 1}) + >>> db.test.count_documents({"x": 1}) 3 - >>> result = db.test.delete_many({'x': 1}) + >>> result = db.test.delete_many({"x": 1}) >>> result.deleted_count 3 - >>> db.test.count_documents({'x': 1}) + >>> db.test.count_documents({"x": 1}) 0 :param filter: A query that matches the documents to delete. @@ -2185,8 +2179,7 @@ def create_indexes( """Create one or more indexes on this collection. >>> from pymongo import IndexModel, ASCENDING, DESCENDING - >>> index1 = IndexModel([("hello", DESCENDING), - ... ("world", ASCENDING)], name="hello_world") + >>> index1 = IndexModel([("hello", DESCENDING), ("world", ASCENDING)], name="hello_world") >>> index2 = IndexModel([("goodbye", DESCENDING)]) >>> db.test.create_indexes([index1, index2]) ["hello_world", "goodbye_-1"] @@ -2504,7 +2497,6 @@ def list_indexes( >>> for index in db.test.list_indexes(): ... print(index) - ... SON([('v', 2), ('key', SON([('_id', 1)])), ('name', '_id_')]) Cursors are closed automatically when they are exhausted (the last batch of data is @@ -3058,8 +3050,9 @@ def aggregate_raw_batches( :mod:`bson` module. >>> import bson - >>> cursor = db.test.aggregate_raw_batches([ - ... {'$project': {'x': {'$multiply': [2, '$x']}}}]) + >>> cursor = db.test.aggregate_raw_batches( + ... [{"$project": {"x": {"$multiply": [2, "$x"]}}}] + ... ) >>> for batch in cursor: ... print(bson.decode_all(batch)) @@ -3326,32 +3319,30 @@ def find_one_and_delete( ) -> _DocumentType | None: """Find a single document and delete it, returning the document. - >>> db.test.count_documents({'x': 1}) + >>> db.test.count_documents({"x": 1}) 2 - >>> db.test.find_one_and_delete({'x': 1}) + >>> db.test.find_one_and_delete({"x": 1}) {'x': 1, '_id': ObjectId('54f4e12bfba5220aa4d6dee8')} - >>> db.test.count_documents({'x': 1}) + >>> db.test.count_documents({"x": 1}) 1 Returns ``None`` if no document matches the filter. - >>> db.test.find_one_and_delete({'_exists': False}) + >>> db.test.find_one_and_delete({"_exists": False}) If multiple documents match *filter*, a *sort* can be applied. - >>> for doc in db.test.find({'x': 1}): + >>> for doc in db.test.find({"x": 1}): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> db.test.find_one_and_delete( - ... {'x': 1}, sort=[('_id', pymongo.DESCENDING)]) + >>> db.test.find_one_and_delete({"x": 1}, sort=[("_id", pymongo.DESCENDING)]) {'x': 1, '_id': 2} The *projection* option can be used to limit the fields returned. - >>> db.test.find_one_and_delete({'x': 1}, projection={'_id': False}) + >>> db.test.find_one_and_delete({"x": 1}, projection={"_id": False}) {'x': 1} :param filter: A query that matches the document to delete. @@ -3424,17 +3415,17 @@ def find_one_and_replace( Return either the original or the replaced document. - >>> db.test.find_one({'x': 1}) + >>> db.test.find_one({"x": 1}) {'_id': 0, 'x': 1} - >>> db.test.find_one_and_replace({'x': 1}, {'y': 2}) + >>> db.test.find_one_and_replace({"x": 1}, {"y": 2}) {'_id': 0, 'x': 1} - >>> db.test.find_one({'x': 1}) - >>> db.test.find_one({'y': 2}) + >>> db.test.find_one({"x": 1}) + >>> db.test.find_one({"y": 2}) {'_id': 0, 'y': 2} Returns ``None`` if no document matches the filter. - >>> db.test.find_one_and_replace({'_exists': False}, {'x': 1}) + >>> db.test.find_one_and_replace({"_exists": False}, {"x": 1}) The :meth:`find_one_and_replace` method differs from :meth:`find_one_and_update` by replacing the document matched by @@ -3442,15 +3433,13 @@ def find_one_and_replace( >>> for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} - >>> db.test.find_one_and_replace({'x': 1}, {'y': 1}) + >>> db.test.find_one_and_replace({"x": 1}, {"y": 1}) {'x': 1, '_id': 0} >>> for doc in db.test.find({}): ... print(doc) - ... {'y': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} @@ -3545,18 +3534,18 @@ def find_one_and_update( Return either the original or the updated document. - >>> db.test.find_one({'_id': 665}) + >>> db.test.find_one({"_id": 665}) {'_id': 665, 'done': False, 'count': 25} >>> db.test.find_one_and_update( - ... {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}}) + ... {"_id": 665}, {"$inc": {"count": 1}, "$set": {"done": True}} + ... ) {'_id': 665, 'done': False, 'count': 25} - >>> db.test.find_one({'_id': 665}) + >>> db.test.find_one({"_id": 665}) {'_id': 665, 'done': True, 'count': 26} Returns ``None`` if no document matches the filter. - >>> db.test.find_one_and_update( - ... {'_exists': False}, {'$inc': {'count': 1}}) + >>> db.test.find_one_and_update({"_exists": False}, {"$inc": {"count": 1}}) When the filter matches, by default :meth:`find_one_and_update` returns the original version of the document before the update was @@ -3566,18 +3555,18 @@ def find_one_and_update( >>> from pymongo import ReturnDocument >>> db.example.find_one_and_update( - ... {'_id': 'userid'}, - ... {'$inc': {'seq': 1}}, - ... return_document=ReturnDocument.AFTER) + ... {"_id": "userid"}, {"$inc": {"seq": 1}}, return_document=ReturnDocument.AFTER + ... ) {'_id': 'userid', 'seq': 1} You can limit the fields returned with the *projection* option. >>> db.example.find_one_and_update( - ... {'_id': 'userid'}, - ... {'$inc': {'seq': 1}}, - ... projection={'seq': True, '_id': False}, - ... return_document=ReturnDocument.AFTER) + ... {"_id": "userid"}, + ... {"$inc": {"seq": 1}}, + ... projection={"seq": True, "_id": False}, + ... return_document=ReturnDocument.AFTER, + ... ) {'seq': 2} The *upsert* option can be used to create the document if it doesn't @@ -3586,24 +3575,23 @@ def find_one_and_update( >>> (db.example.delete_many({})).deleted_count 1 >>> db.example.find_one_and_update( - ... {'_id': 'userid'}, - ... {'$inc': {'seq': 1}}, - ... projection={'seq': True, '_id': False}, + ... {"_id": "userid"}, + ... {"$inc": {"seq": 1}}, + ... projection={"seq": True, "_id": False}, ... upsert=True, - ... return_document=ReturnDocument.AFTER) + ... return_document=ReturnDocument.AFTER, + ... ) {'seq': 1} If multiple documents match *filter*, a *sort* can be applied. - >>> for doc in db.test.find({'done': True}): + >>> for doc in db.test.find({"done": True}): ... print(doc) - ... {'_id': 665, 'done': True, 'result': {'count': 26}} {'_id': 701, 'done': True, 'result': {'count': 17}} >>> db.test.find_one_and_update( - ... {'done': True}, - ... {'$set': {'final': True}}, - ... sort=[('_id', pymongo.DESCENDING)]) + ... {"done": True}, {"$set": {"final": True}}, sort=[("_id", pymongo.DESCENDING)] + ... ) {'_id': 701, 'done': True, 'result': {'count': 17}} :param filter: A query that matches the document to update. diff --git a/pymongo/synchronous/database.py b/pymongo/synchronous/database.py index 7b0d76ba7b..9f19a4f8f8 100644 --- a/pymongo/synchronous/database.py +++ b/pymongo/synchronous/database.py @@ -104,7 +104,7 @@ def __init__( of :class:`~pymongo.collection.Collection` for attribute names with leading underscores. You must use dict-style lookups instead:: - db['__my_collection__'] + db["__my_collection__"] Not: @@ -174,7 +174,7 @@ def with_options( >>> db1.read_preference Primary() >>> from pymongo.read_preferences import Secondary - >>> db2 = db1.with_options(read_preference=Secondary([{'node': 'analytics'}])) + >>> db2 = db1.with_options(read_preference=Secondary([{"node": "analytics"}])) >>> db1.read_preference Primary() >>> db2.read_preference @@ -265,8 +265,7 @@ def get_collection( >>> coll1.read_preference Primary() >>> from pymongo import ReadPreference - >>> coll2 = db.get_collection( - ... 'test', read_preference=ReadPreference.SECONDARY) + >>> coll2 = db.get_collection("test", read_preference=ReadPreference.SECONDARY) >>> coll2.read_preference Secondary(tag_sets=None) @@ -1292,22 +1291,21 @@ def drop_collection( Queryable Encryption. For example:: { - "escCollection": "enxcol_.encryptedCollection.esc", - "ecocCollection": "enxcol_.encryptedCollection.ecoc", - "fields": [ - { - "path": "firstName", - "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')), - "bsonType": "string", - "queries": {"queryType": "equality"} - }, - { - "path": "ssn", - "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')), - "bsonType": "string" - } - ] - + "escCollection": "enxcol_.encryptedCollection.esc", + "ecocCollection": "enxcol_.encryptedCollection.ecoc", + "fields": [ + { + "path": "firstName", + "keyId": Binary.from_uuid(UUID("00000000-0000-0000-0000-000000000000")), + "bsonType": "string", + "queries": {"queryType": "equality"}, + }, + { + "path": "ssn", + "keyId": Binary.from_uuid(UUID("04104104-1041-0410-4104-104104104104")), + "bsonType": "string", + }, + ], } diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index c4773da537..9128fe380a 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -540,7 +540,7 @@ def __init__( :class:`pymongo.mongo_client.MongoClient`. For example, to override the system default CA file:: - kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}} + kms_tls_options = {"kmip": {"tlsCAFile": certifi.where()}} Or to supply a client certificate:: diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index 39c1958313..8475ded172 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -219,20 +219,22 @@ def __init__( from urllib.parse import quote_plus - uri = "mongodb://%s:%s@%s" % ( - quote_plus(user), quote_plus(password), host) + uri = "mongodb://%s:%s@%s" % (quote_plus(user), quote_plus(password), host) client = MongoClient(uri) Unix domain sockets are also supported. The socket path must be percent encoded in the URI:: uri = "mongodb://%s:%s@%s" % ( - quote_plus(user), quote_plus(password), quote_plus(socket_path)) + quote_plus(user), + quote_plus(password), + quote_plus(socket_path), + ) client = MongoClient(uri) But not when passed as a simple hostname:: - client = MongoClient('/tmp/mongodb-27017.sock') + client = MongoClient("/tmp/mongodb-27017.sock") Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The URI must include one, and only one, hostname. The hostname will be @@ -262,10 +264,11 @@ def __init__( like this:: from pymongo.errors import ConnectionFailure + client = MongoClient() try: # The ping command is cheap and does not require auth. - client.admin.command('ping') + client.admin.command("ping") except ConnectionFailure: print("Server not available") @@ -502,6 +505,7 @@ def __init__( def validator(host: str) -> bool: return host.endswith((".a.example.com", ".b.example.com")) + MongoClient( "mongodb+srv://cluster.example.com/", srv_host_validator=validator, @@ -791,7 +795,7 @@ def validator(host: str) -> bool: In PyMongo 2.x, :class:`~pymongo.MongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: - MongoClient(['host1.com:27017', 'host2.com:27017']) + MongoClient(["host1.com:27017", "host2.com:27017"]) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or @@ -825,7 +829,7 @@ def validator(host: str) -> bool: instance of :class:`~pymongo.database.Database` for attribute names with leading underscores. You must use dict-style lookups instead:: - client['__my_database__'] + client["__my_database__"] Not:: @@ -1589,12 +1593,12 @@ def get_default_database( ) -> database.Database[_DocumentType]: """Get the database named in the MongoDB connection URI. - >>> uri = 'mongodb://host/my_database' + >>> uri = "mongodb://host/my_database" >>> client = MongoClient(uri) >>> db = client.get_default_database() - >>> assert db.name == 'my_database' + >>> assert db.name == "my_database" >>> db = client.get_database() - >>> assert db.name == 'my_database' + >>> assert db.name == "my_database" Useful in scripts where you want to choose which database to use based only on the URI in a configuration file. @@ -1659,8 +1663,7 @@ def get_database( >>> db1.read_preference Primary() >>> from pymongo import ReadPreference - >>> db2 = client.get_database( - ... 'test', read_preference=ReadPreference.SECONDARY) + >>> db2 = client.get_database("test", read_preference=ReadPreference.SECONDARY) >>> db2.read_preference Secondary(tag_sets=None) @@ -2575,22 +2578,23 @@ def bulk_write( >>> for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} ... >>> for doc in db.coll.find({}): ... print(doc) - ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} ... >>> # DeleteMany, UpdateOne, and UpdateMany are also available. >>> from pymongo import InsertOne, DeleteOne, ReplaceOne - >>> models = [InsertOne(namespace="db.test", document={'y': 1}), - ... DeleteOne(namespace="db.test", filter={'x': 1}), - ... InsertOne(namespace="db.coll", document={'y': 2}), - ... ReplaceOne(namespace="db.test", filter={'w': 1}, - ... replacement={'z': 1}, upsert=True)] + >>> models = [ + ... InsertOne(namespace="db.test", document={"y": 1}), + ... DeleteOne(namespace="db.test", filter={"x": 1}), + ... InsertOne(namespace="db.coll", document={"y": 2}), + ... ReplaceOne( + ... namespace="db.test", filter={"w": 1}, replacement={"z": 1}, upsert=True + ... ), + ... ] >>> result = client.bulk_write(models=models) >>> result.inserted_count 2 @@ -2602,14 +2606,12 @@ def bulk_write( 1 >>> for doc in db.test.find({}): ... print(doc) - ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')} ... >>> for doc in db.coll.find({}): ... print(doc) - ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} {'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')} diff --git a/pyproject.toml b/pyproject.toml index 90efc5a583..7082999e12 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -184,6 +184,9 @@ disable_error_code = ["unused-coroutine", "no-redef"] line-length = 100 extend-exclude = ["drivers-evergreen-tools"] +[tool.ruff.format] +docstring-code-format = true + [tool.ruff.lint] extend-select = [ "E", "F", "W", # flake8 diff --git a/test/utils_shared.py b/test/utils_shared.py index eb39db8379..9766ee54df 100644 --- a/test/utils_shared.py +++ b/test/utils_shared.py @@ -429,6 +429,7 @@ def delay(sec): import signal + # Raise KeyboardInterrupt in 1 second def sigalarm(num, frame): raise KeyboardInterrupt