@@ -32,25 +32,18 @@ back into the corresponding {+language+} types.
3232The following list shows some {+language+} types that {+driver-short+} can serialize
3333and deserialize:
3434
35- - Strings ( ``str``)
36- - Integers ( ``int``)
37- - Floats ( ``float``)
38- - Booleans ( ``bool``)
39- - Datetimes ( ``datetime.datetime``)
40- - Lists ( ``list``)
41- - Dictionaries ( ``dict``)
42- - None ( ``None``)
43-
44- For a complete list of {+language+}-to-BSON mappings, see the `bson {+api-root+}bson/index.html`__
35+ - ``str``
36+ - ``int``
37+ - ``float``
38+ - ``bool``
39+ - ``datetime.datetime``
40+ - ``list``
41+ - ``dict``
42+ - ``None``
43+
44+ For a complete list of {+language+}-to-BSON mappings, see the `bson < {+api-root+}bson/index.html> `__
4545API documentation.
4646
47- .. note:
48-
49- Because the key-value pairs in {+language+} dictionaries are unordered, the order of
50- fields in serialized BSON documents can differ from the order of fields in the original
51- dictionary. To preserve the order of keys when serializing and deserializing BSON,
52- use the `SON <{+api-root+}bson/son.html>`__ class.
53-
5447Custom Classes
5548--------------
5649
@@ -97,3 +90,34 @@ it back into a ``Restaurant`` object from the preceding example:
9790
9891To learn more about retrieving documents from a collection, see the :ref:`pymongo-retrieve`
9992guide.
93+
94+ Serializing Ordered Documents
95+ -----------------------------
96+
97+ Because the key-value pairs in {+language+} dictionaries are unordered, the order of
98+ fields in serialized BSON documents can differ from the order of fields in the original
99+ dictionary. This behavior can cause issues when {+driver-short+} compares subdocuments
100+ to each other, since {+driver-short+} only considers subdocuments to be equal if their fields
101+ are in identical order.
102+
103+ To preserve the order of keys when serializing and deserializing BSON,
104+ use the `SON <{+api-root+}bson/son.html>`__ class. You must also configure your collection
105+ to use SON for serialization and deserialization by specifying ``document_class=SON``
106+ to the ``with_options`` method of a collection.
107+
108+ The following example retrieves a document
109+ that has a ``location`` field value of ``{"street": "Cafe St", "zipcode": "10003"}`` from
110+ the ``restaurants`` collection:
111+
112+ .. code-block:: python
113+
114+ from bson import CodecOptions, SON
115+
116+ opts = CodecOptions(document_class=SON)
117+ collection = db.get_collection("restaurants")
118+ son_collection = collection.with_options(codec_options=opts)
119+ doc = son_collection.find_one({"location": SON([("street", "Cafe St"), ("zipcode", "10003")])})
120+
121+ For more information about subdocument matching, see the
122+ :manual:`Query on Embedded/Nested Documents </tutorial/query-embedded-documents/>`
123+ guide in the {+mdb-server+} documentation.
0 commit comments