Search code examples
pythonmongodbpymongobsondatabase

Does PyMongo automatically BSON.encode all strings you insert?


I've heard people say that PyMongo automatically uses BSON format for everything you insert in the database. Is this true? Or do I still need to run BSON.encode manually?


Solution

  • The drivers will handle marshaling python builtin objects to their bson counterpart as part of the intermediate layer between you and the database. Ultimately, the data stored in mongodb is bson.

    datetime objects will be saved properly, as will numerics, strings, lists. You do not need to specifically serialize them. A document object is a dictionary.

    The only reason for manual encoding is when you want to give custom classes the ability to be stored, without having to break them down into builtin types. It's very much like any other serialization format (pickle, json, ...). They usually handle the built-ins fine, but need extra help for custom types.