Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MongoDB - BSON to JSON
import pymongo
from datetime import datetime
from pymongo import Connection
conn = Connection()
db = conn['myDB']
collection = db['language']
#Creating a collection
db.language.insert({"id": "1", "name": "C", "grade":"Boring", "timestamp":datetime.now()})
#Reading it
print db.language.find_one({"id":"1"})
# Converting to JSON using json module
import json
print json.dumps(db.language.find_one({"id":"1"}))
# Converting to JSON using Tornado
import tornado.escape
tornado.escape.json_encode(db.language.find_one({"id":"1"}))
# Converting to JSON with bson.json_util of pymongo
from bson.json_util import dumps
print dumps(db.language.find_one({"id":"1"}))
#Deleting the collection
db.language.drop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment