![](/img/trans.png)
[英]How can I copy one collection from MongoDB using pymongo and paste to another empty collection?
[英]Moving records from one collection to another PyMongo
將許多記錄從一個集合移到另一個集合的正確方法是什么? 我所遇到的其他幾個SO職位如本該處理達到同樣的目標,但沒有一個Python實現。
#Taking a number of records from one database and returning the cursor
cursor_excess_new = db.test_collection_new.find().sort([("_id", 1)]).limit(excess_num)
# db.test.insert_many(doc for doc in cursor_excess_new).inserted_ids
# Iterating cursor and Trying to write to another database
# for doc in cursor_excess_new:
# db.test_collection_old.insert_one(doc)
result = db.test_collection_old.bulk_write([
for doc in cursor_excess_new:
InsertMany(doc for each doc in cur)
pprint(doc)
])
如果使用insert_many,則會出現以下錯誤: pymongo.errors.OperationFailure: Writes to config servers must have batch size of 1, found 10
bulk_write在for循環開始時給了我一個語法錯誤。
在pymongo中將記錄從一個集合轉移到另一個集合以使其原子化的最佳實踐和正確方法是什么?
Collection.bulk_write
接受一個可迭代的查詢操作作為參數。
pymongo
有pymongo.operations.InsertOne
操作不InsertMany。
根據您的情況,您可以為源集合中的每個文檔構建一個InsertOne
操作列表。 然后,使用內置的操作列表在目標上執行bulk_write。
from pymongo import InsertOne
...
cursor_excess_new = (
db.test_collection_new
.find()
.sort([("_id", 1)])
.limit(excess_num)
)
queries = [InsertOne(doc) for doc in cursor_excess_new]
db.test_collection_old.bulk_write(queries)
您不需要“ for循環”。
myList=list(collection1.find({}))
collection2.insert_many(myList)
collection1.delete_many({})
如果需要過濾它,可以使用以下代碼:
myList=list(collection1.find({'status':10}))
collection2.insert_many(myList)
collection1.delete_many({'status':10})
但是要小心,因為它沒有成功移動的保證,因此您需要控制交易。 如果要使用以下代碼,則應考慮MongoDb不應該是獨立的,並且需要激活Replication並擁有另一個實例。
with myClient.start_session() as mySession:
with mySession.start_transaction():
...yourcode...
最后,上述代碼具有成功移動(插入和刪除)的擔保,但是交易不在您手中,您無法獲得此交易的結果,因此可以使用以下代碼控制移動和交易:
with myClient.start_session() as mySession:
mySession.start_transaction()
try:
...yourcode...
mySession.commit_transaction()
print("Done")
except Exception as e:
mySession.abort_transaction()
print("Failed",e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.