Skip to content

PYTHON-1359: Add Example for RawBSONDocument #578

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

Merged
merged 6 commits into from
Mar 17, 2021
Merged
Changes from all 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
40 changes: 40 additions & 0 deletions bson/raw_bson.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down