Skip to content

Commit c40a455

Browse files
committed
PYTHON-1359: Add Example for RawBSONDocument (#578)
Add doctest/example for inserting/retrieving RawBSONDocument (cherry picked from commit 8ef4524)
1 parent e958f08 commit c40a455

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

bson/raw_bson.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,46 @@
1313
# limitations under the License.
1414

1515
"""Tools for representing raw BSON documents.
16+
17+
Inserting and Retrieving RawBSONDocuments
18+
=========================================
19+
20+
Example: Moving a document between different databases/collections
21+
22+
.. testsetup::
23+
from pymongo import MongoClient
24+
client = MongoClient(document_class=RawBSONDocument)
25+
client.drop_database('db')
26+
client.drop_database('replica_db')
27+
28+
.. doctest::
29+
30+
>>> import bson
31+
>>> from pymongo import MongoClient
32+
>>> from bson.raw_bson import RawBSONDocument
33+
>>> client = MongoClient(document_class=RawBSONDocument)
34+
>>> db = client.db
35+
>>> result = db.test.insert_many([{'a': 1},
36+
... {'b': 1},
37+
... {'c': 1},
38+
... {'d': 1}])
39+
>>> replica_db = client.replica_db
40+
>>> for doc in db.test.find():
41+
... print(f"raw document: {doc.raw}")
42+
... print(f"decoded document: {bson.decode(doc.raw)}")
43+
... result = replica_db.test.insert_one(doc)
44+
raw document: b'...'
45+
decoded document: {'_id': ObjectId('...'), 'a': 1}
46+
raw document: b'...'
47+
decoded document: {'_id': ObjectId('...'), 'b': 1}
48+
raw document: b'...'
49+
decoded document: {'_id': ObjectId('...'), 'c': 1}
50+
raw document: b'...'
51+
decoded document: {'_id': ObjectId('...'), 'd': 1}
52+
53+
For use cases like moving documents across different databases or writing binary
54+
blobs to disk, using raw BSON documents provides better speed and avoids the
55+
overhead of decoding or encoding BSON.
1656
"""
1757

1858
from bson import _raw_to_dict, _get_object_size

0 commit comments

Comments
 (0)