douwan2664 2019-01-09 20:09
浏览 597
已采纳

使用golang从MongoDB批量获取记录

How can one fetch records in batches from a mongo database using golang? I know mongoDB itself has something called cursor.batchSize(), but im trying to find an example using a golang driver. From what I've seen the golang library mgo has a function called Batch, but Im trying to figure out how to us it.

Ideally I'm looking for something like this:

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++;
    }
}

I have something like this so far:

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

But it's not working like expected.

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

  • 写回答

1条回答 默认 最新

  • dongren7374 2019-01-10 03:51
    关注

    The batchSize() specifies the number of documents to return in each batch of the response. You will still all results. For example, if the total number of returned docs is 100 and you specify batch size as 20, you will have 1 find and 4 getMore commands sent from the client to the mongod to complete the request.

    One little trick you can use to verify. Use db.setProfilingLevel(0, 0) from mongo shell to log everything in the log file. Execute your test app and you will see find and getMore recorded in the log.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载