登录
首页 >  Golang >  Go问答

Mongodb无法在超过200万条记录的集合中使用游标检索所有文档

来源:stackoverflow

时间:2024-02-26 22:48:25 415浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《Mongodb无法在超过200万条记录的集合中使用游标检索所有文档》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我收藏了 2,000,000 条记录

> db.events.count();                                     │
2000000

我使用golang mongodb客户端连接数据库

package main

import (
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
    ctx, cancel := context.withtimeout(context.background(), 10*time.second)
    defer cancel()
    client, err := mongo.connect(ctx, options.client().applyuri("mongodb://localhost:27888").setauth(options.credential{
        username: "mongoadmin",
        password: "secret",
    }))

    if err != nil {
        panic(err)
    }

    defer func() {
        if err = client.disconnect(ctx); err != nil {
            panic(err)
        }
    }()


    collection := client.database("test").collection("events")

    var bs int32 = 10000
    var b = true
    cur, err := collection.find(context.background(), bson.d{}, &options.findoptions{
        batchsize: &bs, nocursortimeout: &b})
    if err != nil {
        log.fatal(err)
    }
    defer cur.close(ctx)

    s, n := runningtime("retrive db from mongo and publish to kafka")
    count := 0
    for cur.next(ctx) {
        var result bson.m
        err := cur.decode(&result)
        if err != nil {
            log.fatal(err)
        }

        bytes, err := json.marshal(result)
        if err != nil {
            log.fatal(err)
        }
        count++

        msg := &sarama.producermessage{
            topic: "hello",
            // key:   sarama.stringencoder("akey"),
            value: sarama.byteencoder(bytes),
        }
        asyncproducer.input() <- msg
    }


但是该程序仅检索大约 600,000 条记录,而不是每次运行该程序时检索 2,000,000 条记录。

$ go run main.go
done
count = 605426
nErrors = 0
2020/09/18 11:23:43 End:         retrive db from mongo and publish to kafka took 10.080603336s

不知道为什么?我想检索所有 2,000,000 条记录。感谢您的帮助。


解决方案


获取结果的循环可能会提前结束,因为您使用相同的 ctx 上下文来迭代具有 10 秒超时的结果。

这意味着如果检索和处理这200万条记录(包括连接)需要超过10秒,上下文将被取消,因此游标也会报告错误。

请注意,将 FindOptions.NoCursorTimeout 设置为 true 只是为了防止光标因不活动而超时,它不会覆盖所使用的上下文的超时。

使用另一个上下文来执行查询并迭代结果,一个没有超时的上下文,例如context.Background()

另请注意,要构造 find 的选项,请使用辅助方法,因此它可能看起来像这样简单而优雅:

options.find().setbatchsize(10000).setnocursortimeout(true)

所以工作代码:

ctx2 := context.Background()

cur, err := collection.Find(ctx2, bson.D{},
    options.Find().SetBatchSize(10000).SetNoCursorTimeout(true))

// ...

for cur.Next(ctx2) {
    // ...
}

// Also check error after the loop:
if err := cur.Err(); err != nil {
    log.Printf("Iterating over results failed: %v", err)
}

到这里,我们也就讲完了《Mongodb无法在超过200万条记录的集合中使用游标检索所有文档》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>