Last active
January 13, 2016 06:44
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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