Skip to content

Instantly share code, notes, and snippets.

@sindbach
Last active January 13, 2016 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sindbach/fd3eb52747f467576f16 to your computer and use it in GitHub Desktop.
Save sindbach/fd3eb52747f467576f16 to your computer and use it in GitHub Desktop.
A simple Python example on how to serialise/deserialise MongoDB ObjectID() using PyYAML.
import yaml
from pymongo import MongoClient
from bson import objectid
def objectid_representer(dumper, data):
return dumper.represent_scalar("!bson.objectid.ObjectId", str(data))
def objectid_constructor(loader, data):
return objectid.ObjectId(loader.construct_scalar(data))
def sample_mongodb_doc():
client = MongoClient()
return client.test.yaml.find_one()
def main():
# Fetch a single document from MongoDB, which contains {_id:ObjectID(...)}.
doc = sample_mongodb_doc()
print(doc)
# Serialise dict containing ObjectID into yaml file.
yamlfile = open('data.yaml', 'wb')
yaml.SafeDumper.add_representer(objectid.ObjectId, objectid_representer)
yaml.safe_dump(doc, yamlfile, default_flow_style=False)
yamlfile.close()
# Deserialise yaml file back into a dict.
yaml.add_constructor('!bson.objectid.ObjectId', objectid_constructor)
loaded = yaml.load(open('data.yaml', 'r'))
print(loaded)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment