我预先过滤了3个集合,然后从中建立一个新的集合。要做到这一点,我像这样遍历游标对象(monate, wochen, tage是包含相关的 datetime
对象。
monate_final = collection1.find({"NewDate": {"$in": list(monate)}})
wochen_final = collection2.find({"NewDate": {"$in": list(wochen)}})
tage_final = collection3.find({"NewDate": {"$in": list(tage)}})
master_list = [monate_final, wochen_final, tage_final]
for collection in master_list:
for document in collection:
self.target.insert_one(document)
但由于最后的集合包含了1亿条记录,所以这个过程需要很长时间。我没有找到更有效的方法。构建一个大熊猫 DataFrame
再用 insert_many()
由于内存限制,无法工作。谁能帮帮我?
使用批量操作,并将批量写入的数据分成若干块,比如说,像这个例子中的50,000块。你可以使用计数器(可能更快)或者直接检查 len(updates)
:
from pymongo import InsertOne
updates = []
counter = 0
for collection in master_list:
for document in collection:
updates.append(InsertOne(document))
counter += 1
if counter > 50000:
self.target.bulk_write(updates)
counter = 0
updates = []
# Update the final items after the cursor has exhausted
if len(updates) != 0:
self.target.bulk_write(updates)
我没有足够的声誉来做这个评论。
我还没有验证这一点。但你可以做一个聚合管道,过滤你的集合。而管道的最后一步是$out操作符,将管道中的所有文档保存到新的集合中。
https:/docs.mongodb.commanualreferenceoperatoraggregationout
从MongoDB来看,我对内部的工作原理并不深入。但我希望管道能完全在DB端运行,这将大大提高操作的性能。
祝你能解决这个问题! (别忘了把你的解决方法加给别人:D)