Encode a document to BSON. A document can be any mapping type (like :class:`dict`). Raises :class:`TypeError` if `document` is not a mapping type, or contains keys that are not instances of :class:`str`. Raises :class:`~bson.errors.InvalidDocument` if `document` cannot be conve
(
document: Mapping[str, Any],
check_keys: bool = False,
codec_options: CodecOptions[Any] = DEFAULT_CODEC_OPTIONS,
)
| 1025 | |
| 1026 | |
| 1027 | def encode( |
| 1028 | document: Mapping[str, Any], |
| 1029 | check_keys: bool = False, |
| 1030 | codec_options: CodecOptions[Any] = DEFAULT_CODEC_OPTIONS, |
| 1031 | ) -> bytes: |
| 1032 | """Encode a document to BSON. |
| 1033 | |
| 1034 | A document can be any mapping type (like :class:`dict`). |
| 1035 | |
| 1036 | Raises :class:`TypeError` if `document` is not a mapping type, |
| 1037 | or contains keys that are not instances of :class:`str`. Raises |
| 1038 | :class:`~bson.errors.InvalidDocument` if `document` cannot be |
| 1039 | converted to :class:`BSON`. |
| 1040 | |
| 1041 | :param document: mapping type representing a document |
| 1042 | :param check_keys: check if keys start with '$' or |
| 1043 | contain '.', raising :class:`~bson.errors.InvalidDocument` in |
| 1044 | either case |
| 1045 | :param codec_options: An instance of |
| 1046 | :class:`~bson.codec_options.CodecOptions`. |
| 1047 | |
| 1048 | .. versionadded:: 3.9 |
| 1049 | """ |
| 1050 | if not isinstance(codec_options, CodecOptions): |
| 1051 | raise _CODEC_OPTIONS_TYPE_ERROR |
| 1052 | |
| 1053 | return _dict_to_bson(document, check_keys, codec_options) |
| 1054 | |
| 1055 | |
| 1056 | @overload |