使用golang从MongoDB批量获取记录

Get records in batches from MongoDB using golang

如何使用 golang 从 mongo 数据库中批量获取记录?我知道 mongoDB 本身有一个叫做 cursor.batchSize() 的东西,但我试图找到一个使用 golang 驱动程序的例子。据我所知,golang 库 mgo 有一个名为 Batch 的函数,但我想弄清楚如何使用它。

理想情况下,我正在寻找这样的东西:

const cursor = useDb.collection(mycollection).find().batchSize(10000);
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
    if (doc._id % divisor === 0) {
        counter++;
    }
}

到目前为止我有这样的东西:

err := c.Find(nil).Batch(1).All(&items)

但它并没有像预期的那样工作。

链接: https://docs.mongodb.com/manual/reference/method/cursor.batchSize/ https://godoc.org/github.com/globalsign/mgo#Query.Batch

batchSize() 指定每批响应中 return 的文档数。你仍然会得到所有的结果。例如,如果 returned 文档的总数是 100,而您将批量大小指定为 20,那么您将有 1 个 find 和 4 个 getMore 命令从客户端发送到 mongod 完成请求。

一个小技巧可以用来验证。使用 mongo shell 中的 db.setProfilingLevel(0, 0) 将所有内容记录在日志文件中。执行您的测试应用程序,您将看到 findgetMore 记录在日志中。