Created
March 13, 2019 20:12
-
-
Save jaraco/8a2dbc7edf3760ceaa6b470b1df560bb to your computer and use it in GitHub Desktop.
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
__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