2017-05-31 104 views
0

我是爲了插入到我的數據庫適當的價格使用MongoDB的3.4 ..的Python - Pymongo MongoDB的3.4 - NumberDecimal

據:

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

我在Python代碼中使用這樣的:

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

但拋出:

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

那麼使用python在mongodb中插入numberdecimal的正確語法是什麼?

感謝和問候

回答

-1

您所提供的鏈接告訴你有關從擴展JSON閱讀。如果您想將它插入一個小數,你應該只使用:

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

'{0:.2f}'.format(9.99)部分將格式化您傳遞(在這種情況下9.99)的數量,包括每次2位小數。所以'{0:.2f}'.format(9)應該在你的數據庫中產生9.00。

+0

你的語法同樣適用於9.99 ...但我總是需要它插入一個雙,也爲「9」和「9.00」,你知道嗎? –

+0

更新了我的答案...另外,爲什麼downvote? :) – errata

0

簡單:

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

(其中「$ numberDecimal」語法是一個JSON字符串中表示十進制數,但你不使用JSON的。)