PyMongo Converting between BSON and JSON Using python-bsonjs


python-bsonjs does not depend on PyMongo and can offer a nice performance improvement over json_util:

bsonjs is roughly 10-15x faster than PyMongo’s json_util at decoding BSON to JSON and encoding JSON to BSON.

Note that:

  • to use bsonjs effectively, it is recommended to work directly with RawBSONDocument
  • dates are encoded using the LEGACY representation, i.e. {"$date": <dateAsMilliseconds>}. There is currently no options to change that.


pip install python-bsonjs


To take full advantage of the bsonjs, configure the database to use the RawBSONDocument class. Then, use dumps to convert bson raw bytes to json and loads to convert json to bson raw bytes:

import pymongo
import bsonjs
from pymongo import MongoClient
from bson.raw_bson import RawBSONDocument

# configure mongo to use the RawBSONDocument representation
db = pymongo.MongoClient(document_class=RawBSONDocument).samples
# convert json to a bson record
json_record = '{"_id": "some id", "title": "Awesome Movie"}' 
raw_bson = bsonjs.loads(json_record)
bson_record = RawBSONDocument(raw_bson)
# insert the record
result = db.movies.insert_one(bson_record)

# find some record
bson_record2 = db.movies.find_one()
# convert the record to json
json_record2 = bsonjs.dumps(bson_record2.raw)