Python - Pymongo MongoDB 3.4 - NumberDecimal

好久不见. 提交于 2020-06-18 09:07:13

问题


i am using mongodb 3.4 in order to insert proper prices to my database..

According to:

https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst#reading-from-extended-json

i used this in my python code:

'credits': {'$numberDecimal': Decimal128('9.99')},

but throws:

bson.errors.InvalidDocument: key '$numberDecimal' must not start with '$'

So what is the correct syntax for inserting numberdecimal in mongodb using python ?

thanks and greetings


回答1:


Simply this:

collection.insert_one({'credits': Decimal128('9.99')})

(The "$numberDecimal" syntax is for expressing a decimal number within a JSON string. But you're not using JSON at all.)




回答2:


The link you provided tells you about reading from extended JSON. If you want to insert it as a decimal, you should just use:

{ 'credits': '{0:.2f}'.format(9.99) }

The '{0:.2f}'.format(9.99) part will format the number you pass (in this case 9.99) to include 2 decimals every time. So '{0:.2f}'.format(9) should result in 9.00 in your database.



来源:https://stackoverflow.com/questions/44283527/python-pymongo-mongodb-3-4-numberdecimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!