我最近开始通过shell和PyMongo测试MongoDB.我注意到,返回光标并try 在其上迭代似乎是实际迭代中的瓶颈.有没有一种方法可以在迭代过程中返回多个文档?

伪代码:

for line in file:
    value = line[a:b]
    cursor = collection.find({"field": value})
    for entry in cursor:
        (deal with single entry each time)

我希望这样做:

for line in file
    value = line[a:b]
    cursor = collection.find({"field": value})
    for all_entries in cursor:
        (deal with all entries at once rather than iterate each time)

我try 过按照this question使用batch_size(),并将值一直更改为this question0000,但似乎没有任何效果(或者我做错了).

非常感谢您的帮助.请对这个Mongo新手放松点!

---编辑---

谢谢你,凯勒.我想你已经指出了我真正想问的问题,那就是:有没有办法像cx_Oracle模块那样执行某种collection.findAll()cursor.fetchAll()命令?问题不是存储数据,而是尽可能快地从Mongo DB检索数据.

据我所知,数据返回给我的速度是由我的网络决定的,因为Mongo必须单次获取每条记录,对吗?

推荐答案

您是否考虑过以下方法:

for line in file
  value = line[a:b]
  cursor = collection.find({"field": value})
  entries = cursor[:] # or pull them out with a loop or comprehension -- just get all the docs
  # then process entries as a list, either singly or in batch

或者,类似于:

# same loop start
  entries[value] = cursor[:]
# after the loop, all the cursors are out of scope and closed
for value in entries:
  # process entries[value], either singly or in batch

基本上,只要你有足够的内存来存储你的结果集,你就应该能够把它们从游标上拉下来,并在处理之前抓住它们.这不太可能明显更快,但它将缓解任何特定于游标的减速,并且如果您已经做好了并行处理数据的准备,那么您可以自由地并行处理数据.

Mongodb相关问答推荐

$mod只支持数字类型,不支持MongoDb中的array和int

使用 multer 在我的 MERN 前端显示 MongoDB 图像的正确语法是什么?

通过 docker 运行的 MongoDB 服务器无法互相看到(名称解析中的临时故障)

Nestjs中不同语言数据的mongodb聚合代码

MongoDB:插入重复键更新

MongoDB中的readPreference和readConcern有什么区别?

使用 EventSourcing(NodeJS、MongoDB、JSON)跨多个偶尔连接的客户端同步数据

获取收集字节使用情况统计信息的pymongo方法?

Java MongoDB/BSON 类混淆

如何在 mongodb 本机驱动程序中对 find() 进行字段 Select ?

在 Mongo 中存储嵌套类别的最有效方法?

在 mongoDB 中展平嵌套的 JSON struct

REACT 获取发布请求

MongoDB 日志(log)文件和 oplog 有何不同?

如何使用 mgo 和 Go 查询 MongoDB 的日期范围?

如何在 MongoDB Map-reduce 映射函数中使用变量

使用 Node.js 将许多记录插入 Mongodb 的正确方法

如何将转储文件夹导入 mongodb 数据库?

如何匹配 MongoDB 聚合框架中的 undefined值?

python + pymongo:如何从 for 循环中在 mongo 中的现有文档上插入新字段