[英]How to print a value in Python that is inside a Json in MongoDB object
[英]How to print and calculate a value in Python that is inside a Json in MongoDB
我在mongodb中有這個Json
{
"_id" : ObjectId("5aba203f00435837802f9c49"),
"AED" : 4.572098,
"AFN" : 86.093419,
"ALL" : 130.478529,
"AMD" : 597.524404,
"ANG" : 2.216574,
"AOA" : 264.413246,
}
而這在Python中
import pymongo
uri = "mongodb://127.0.0.1:27017"
client= pymongo.MongoClient(uri)
database = client['countries_db']
collection = database['currency']
currency =[AED['AED'] for AED in collection.find({})]
res=currency*2
print(res)
輸出:[4.572098、4.572098]
當我打印時,它是一個字符串值,它會重復AED兩次。 有什么方法可以將值稱為float並進行計算? 謝謝。
問題不在於它正在返回一個字符串值。 它正在返回一個列表。 當您嘗試將一個列表相乘時,它只會重復自身多次,這就是您在此處看到的。 如何解決它取決於您希望從find()
操作中獲取多少元素以及您希望對它們進行全部處理。
如果期望find()
操作的結果是1個元素,則應將其轉換為find_one()
,該find_one()
將返回浮點數,並通過以下代碼使乘法操作按預期工作:
item = collection.find_one({}) # Returns a single doc. Note the lack of square brackets currency = item['AED'] # Get the desired key of the document res = currency * 2
如果期望元素多於1個,則可以通過使用res = map(lambda x: x*2, currency)
在其上運行地圖來將每個返回值乘以2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.