Skip to content

Instantly share code, notes, and snippets.

@jaraco
Created March 13, 2019 20:13
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 jaraco/da813c73a12f7a47157fec11d93427c6 to your computer and use it in GitHub Desktop.
Save jaraco/da813c73a12f7a47157fec11d93427c6 to your computer and use it in GitHub Desktop.
__requires__ = ['pymongo']
__index_url__ = 'https://m.devpi.net/jaraco/dev'
import datetime
import decimal
import pymongo
import bson.codec_options as opts
from bson import decimal128
class DecimalCodec(opts.TypeCodecBase):
python_type = decimal.Decimal
bson_type = decimal128.Decimal128
transform_python = decimal128.Decimal128
def transform_bson(self, value):
return value.to_decimal()
url = 'mongodb://localhost/test'
tz_aware = opts.CodecOptions(tz_aware=True, tzinfo=datetime.timezone.utc)
db = pymongo.MongoClient(url).get_database(codec_options=tz_aware)
codec = DecimalCodec()
registry = opts.TypeRegistry(codec)
doc = dict(now=datetime.datetime.now(), val=decimal128.Decimal128('1.0'))
db.coll.drop()
db.coll.insert_one(doc)
# query db.coll using the type registry
print(list(db.coll.with_options(
codec_options=db.coll.codec_options.with_options(type_registry=registry),
).find({})))
db.coll.drop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment