MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / BSON

Class BSON

bson/__init__.py:1400–1468  ·  view source on GitHub ↗

BSON (Binary JSON) data. .. warning:: Using this class to encode and decode BSON adds a performance cost. For better performance use the module level functions :func:`encode` and :func:`decode` instead.

Source from the content-addressed store, hash-verified

1398
1399
1400class BSON(bytes):
1401 """BSON (Binary JSON) data.
1402
1403 .. warning:: Using this class to encode and decode BSON adds a performance
1404 cost. For better performance use the module level functions
1405 :func:`encode` and :func:`decode` instead.
1406 """
1407
1408 @classmethod
1409 def encode(
1410 cls: Type[BSON],
1411 document: Mapping[str, Any],
1412 check_keys: bool = False,
1413 codec_options: CodecOptions[Any] = DEFAULT_CODEC_OPTIONS,
1414 ) -> BSON:
1415 """Encode a document to a new :class:`BSON` instance.
1416
1417 A document can be any mapping type (like :class:`dict`).
1418
1419 Raises :class:`TypeError` if `document` is not a mapping type,
1420 or contains keys that are not instances of
1421 :class:`str'. Raises :class:`~bson.errors.InvalidDocument`
1422 if `document` cannot be converted to :class:`BSON`.
1423
1424 :param document: mapping type representing a document
1425 :param check_keys: check if keys start with '$' or
1426 contain '.', raising :class:`~bson.errors.InvalidDocument` in
1427 either case
1428 :param codec_options: An instance of
1429 :class:`~bson.codec_options.CodecOptions`.
1430
1431 .. versionchanged:: 3.0
1432 Replaced `uuid_subtype` option with `codec_options`.
1433 """
1434 return cls(encode(document, check_keys, codec_options))
1435
1436 def decode( # type:ignore[override]
1437 self, codec_options: CodecOptions[Any] = DEFAULT_CODEC_OPTIONS
1438 ) -> dict[str, Any]:
1439 """Decode this BSON data.
1440
1441 By default, returns a BSON document represented as a Python
1442 :class:`dict`. To use a different :class:`MutableMapping` class,
1443 configure a :class:`~bson.codec_options.CodecOptions`::
1444
1445 >>> import collections # From Python standard library.
1446 >>> import bson
1447 >>> from bson.codec_options import CodecOptions
1448 >>> data = bson.BSON.encode({'a': 1})
1449 >>> decoded_doc = bson.BSON(data).decode()
1450 <type 'dict'>
1451 >>> options = CodecOptions(document_class=collections.OrderedDict)
1452 >>> decoded_doc = bson.BSON(data).decode(codec_options=options)
1453 >>> type(decoded_doc)
1454 <class 'collections.OrderedDict'>
1455
1456 :param codec_options: An instance of
1457 :class:`~bson.codec_options.CodecOptions`.

Calls

no outgoing calls