![](/img/trans.png)
[英]How do I copy the indexes from one collection to another collection using PyMongo?
[英]How can I copy one collection from MongoDB using pymongo and paste to another empty collection?
我接下來做:
db = client["database"]
home = db['home'].find() # get collection.
db['home'].remove({}) # remove doc from home
for i in home:
self.db['home'].insert(i)
但是集合是空的。
您的代碼示例的問題在於find()
將數據庫游標返回到集合,而不是集合中的所有文檔。 因此,當您從home
集合中remove
所有文檔時,光標也將指向一個空集合。
為了將集合復制到同一服務器中的另一個集合,您可以使用MongoDB 聚合運算符$match和$out
pipeline = [ {"$match": {}},
{"$out": "destination_collection"},
]
db.source_collection.aggregate(pipeline)
使用您的示例代碼,現在您可以執行
source = db["source_collection"]
destination = db["destination_collection"]
# Remove all documents, or make modifications.
source.remove({})
# Restore documents from the source collection.
for doc in destination:
source.insert(doc)
# or instead you can just use the same aggregation method above but reverse the collection name.
注意: db.collection.copyTo()自 MongoDB v3.0 起已被棄用。
如果您想復制到另一個 MongoDB 服務器,您可以使用db.cloneCollection() 。 在 PyMongo 中,它將是如下命令:
db.command("cloneCollection", **{'collection': "databaseName.source_collection", 'from': "another_host:another_port"})
根據您的總體目標,您可能會發現MongoDB 備份方法很有用。
這可能是最簡單的方法,我個人更喜歡它,因此您可以添加任意數量的過濾器:
from pymongo import MongoClient
def CopyFromColl1ToColl2(database1,collection1,database2,collection2):
db1 = MongoClient('mongodb://127.0.0.1:27017')[database1][collection1]
db2 = MongoClient('mongodb://127.0.0.1:27017')[database2][collection2]
#here you can put the filters you like.
for a in db1.find():
try:
db2.insert(a)
print(a)
except:
print('did not copy')
# You can choose the database name and the collection name
CopyFromColl1ToColl2('database1','collection1','database2','collection2')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.