使用pymongo读取和更新mongodb文档的最佳方法

wud*_*ker 7 python mongodb pymongo mongodb-query

我试图按文档读取mongodb集合文档,以便获取每条记录加密记录中的一些字段并将其放回数据库.

for record in coll.find():
    #modifying record here
    coll.update(record)
Run Code Online (Sandbox Code Playgroud)

这导致严重的问题,即已经更新的文档被光标再次读取,同一文档再次在循环中处理(同一文档试图再次更新)

希望这可能是解决问题的方法之一.

list_coll = [record for record in coll.find()]
for rec in list_coll:
   #modifying record
   coll.update(rec)
Run Code Online (Sandbox Code Playgroud)

但这是最好的做法吗?即如果集合很大会发生什么?可以大的list_coll导致ram溢出?请建议我这样做的最佳方式.

谢谢

Nei*_*unn 8

您需要MongoDB 的"批量操作API".主要是与MongoDB 2.6一起推出的,所以如果你现在还没有进行升级,这是一个令人信服的理由.

bulk = db.coll.initialize_ordered_bulk_op()
counter = 0

for record in coll.find(snapshot=True):
    # now process in bulk
    # calc value first
    bulk.find({ '_id': record['_id'] }).update({ '$set': { 'field': newValue } })
    counter += 1

    if counter % 1000 == 0:
        bulk.execute()
        bulk = db.coll.initialize_ordered_bulk_op()

if counter % 1000 != 0:
    bulk.execute()
Run Code Online (Sandbox Code Playgroud)

更好的是因为您没有向服务器发送"每个"请求,每1000个请求中只发送一次."批量API"实际上对你有所帮助,但实际上你想要"管理"这个更好一点,而不是在你的应用程序中消耗太多内存.

未来之路.用它.