![](/img/trans.png)
[英]How to return field of record after update query with upsert as true in mongodb using pymongo?
[英]update multiple record from dataframe into mongoDB with upsert=True
我有一個包含近 120000 條記錄的數據框,如下所示。 我還有一個 mongoDB 集合,它看起來與下面的數據框完全一樣
ItemID ParentID ItemRating ItemPrice Qty
A1 ItemA1 0 12 100
A2 ItemA2 0 15 200
B1 ItemB1 0 20 300
B2 ItemB2 0 25 400
B3 ItemB3 0 30 150
現在,我想使用以下條件將數據幀中的記錄更新和插入到 mongo 集合中
我知道這可以通過設置 upsert=true 使用 PyMongo update_many 方法來完成。 但我不確定我該怎么做? 我應該如何寫我的過濾條件?
問候 Vipul
您將無法使用update_many()
因為它采用單個過濾條件,在您的情況下將不起作用。 您需要的是在 upsert=true 的循環中使用replace_one()
。 就像是:
from pymongo import MongoClient
import pandas as pd
db = MongoClient('localhost', 27019)['testdatabase1']
df = pd.DataFrame({'ItemID':['A1','A2','B1','B2','B3'],
'ParentID':['ItemA1','ItemA2','ItemB1','ItemB2','ItemB3'],
'ItemRating ': [0,0,0,0,0],
'ItemPrice ': [12,15,20,25,30],
'Qty': [100,200,300,400,150]
})
for row in df.iterrows():
record = row[1].to_dict()
result = db.testcollection.replace_one({'ItemId': record.get('ItemId'), 'ParentID': record.get('ParentID')}, record, upsert=True)
print(f'{"Replaced: " if result.modified_count == 1 else ""}{"Inserted: " if result.upserted_id is not None else ""} {record}')
由於您正在處理大量數據,因此您可能希望使用bulk_write()
將其壓縮為單個數據庫事務,以執行您使用數據幀標准編譯的ReplaceOne
操作列表。 請參閱PyMongo:批量寫入操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.