问题
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