From 8ef452407649786574cb70dcf0ccd97c16813651 Mon Sep 17 00:00:00 2001 From: William Zhou Date: Wed, 17 Mar 2021 16:15:22 -0700 Subject: [PATCH] PYTHON-1359: Add Example for RawBSONDocument (#578) Add doctest/example for inserting/retrieving RawBSONDocument --- bson/raw_bson.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/bson/raw_bson.py b/bson/raw_bson.py index 31b0d1b66..4ee0394ad 100644 --- a/bson/raw_bson.py +++ b/bson/raw_bson.py @@ -13,6 +13,46 @@ # limitations under the License. """Tools for representing raw BSON documents. + +Inserting and Retrieving RawBSONDocuments +========================================= + +Example: Moving a document between different databases/collections + +.. testsetup:: + from pymongo import MongoClient + client = MongoClient(document_class=RawBSONDocument) + client.drop_database('db') + client.drop_database('replica_db') + +.. doctest:: + + >>> import bson + >>> from pymongo import MongoClient + >>> from bson.raw_bson import RawBSONDocument + >>> client = MongoClient(document_class=RawBSONDocument) + >>> db = client.db + >>> result = db.test.insert_many([{'a': 1}, + ... {'b': 1}, + ... {'c': 1}, + ... {'d': 1}]) + >>> replica_db = client.replica_db + >>> for doc in db.test.find(): + ... 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': ObjectId('...'), 'a': 1} + raw document: b'...' + decoded document: {'_id': ObjectId('...'), 'b': 1} + raw document: b'...' + decoded document: {'_id': ObjectId('...'), 'c': 1} + raw document: b'...' + decoded document: {'_id': ObjectId('...'), 'd': 1} + +For use cases like moving documents across different databases or writing binary +blobs to disk, using raw BSON documents provides better speed and avoids the +overhead of decoding or encoding BSON. """ from collections.abc import Mapping as _Mapping