son – Tools for working with SON, an ordered mapping

Tools for creating and manipulating SON, the Serialized Ocument Notation.

Regular dictionaries can be used instead of SON objects, but not when the order of keys is important. A SON object can be used just like a normal Python dictionary.

class pymongo.son.SON(data=None, **kwargs)

SON data.

A subclass of dict that maintains ordering of keys and provides a few extra niceties for dealing with SON. SON objects can be saved and retrieved from Mongo.

The mapping from Python types to Mongo types is as follows:

Python Type Mongo Type Supported Direction
None null both
bool boolean both
int number (int) both
float number (real) both
string string py -> mongo
unicode string both
list array both
dict / SON object both
datetime.datetime [1] [2] date both
compiled re regex both
pymongo.binary.Binary binary both
pymongo.objectid.ObjectId oid both
pymongo.dbref.DBRef dbref both
None undefined mongo -> py
unicode code mongo -> py
pymongo.code.Code code py -> mongo
unicode symbol mongo -> py

Note that to save binary data it must be wrapped as an instance of pymongo.binary.Binary. Otherwise it will be saved as a Mongo string and retrieved as unicode.

[1]datetime.datetime instances will be rounded to the nearest millisecond when saved
[2]all datetime.datetime instances are treated as naive. clients should always use UTC.
to_dict()

Convert a SON document to a normal Python dictionary instance.

This is trickier than just dict(...) because it needs to be recursive.

Previous topic

message – Tools for creating messages to be sent to MongoDB

Next topic

son_manipulator – Manipulators that can edit SON documents as they are saved or retrieved

This Page