Docs Menu
Docs Home
/ / /
PyMongo

Serialization

On this page

  • Overview
  • Custom Classes
  • Serializing Custom Classes
  • Deserializing Custom Classes

In this guide, you can learn how to use PyMongo to perform serialization.

Serialization is the process of mapping a Python object to a BSON document for storage in MongoDB. PyMongo automatically converts basic Python types into BSON when you insert a document into a collection. Similarly, when you retrieve a document from a collection, PyMongo automatically converts the returned BSON back into the corresponding Python types.

You can use PyMongo to serialize and deserialize the following Python types:

  • str

  • int

  • float

  • bool

  • datetime.datetime

  • list

  • dict

  • None

For a complete list of Python-to-BSON mappings, see the bson API documentation.

To serialize and deserialize custom Python classes, you must implement custom logic to handle the conversion. The following sections show how to serialize and deserialize custom classes.

To serialize a custom class, you must convert the class to a dictionary. The following example serializes a custom class by using the vars() method, and then inserts the serialized object into a collection:

class Restaurant:
def __init__(self, name, cuisine):
self.name = name
self.cuisine = cuisine
restaurant = Guitar("Example Cafe", "Coffee")
restaurant_dict = vars(restaurant)
collection.insert_one(restaurant_dict)

To learn more about inserting documents into a collection, see the Insert Documents guide.

To deserialize a custom class, you must convert the dictionary back into an instance of the class. The following example retrieves a document from a collection, and then converts it back into a Restaurant object from the preceding example:

def deserialize_restaurant(doc):
return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
restaurant_doc = collection.find_one({"name": "Example Cafe"})
restaurant = deserialize_restaurant(restaurant_doc)

To learn more about retrieving documents from a collection, see the Retrieve Data guide.

Back

Monitoring