dsqbh42082 2019-01-03 20:11
浏览 591
已采纳

打印mongoDB Collection Golang中的所有记录

I've got a MongoDB Collection collection := db.Collection("JobBacklog") that I'm trying to print out into the console. The DB is in a Docker container and controlling it with a script written in Go.

From what I've been able to find from the mongo-go-driver https://godoc.org/github.com/mongodb/mongo-go-driver/mongo there is a way to do this but my code keeps returning document is nil when I know it isn't.

This is my code I'm using to try to iterate through a collection called JobBacklog

cur, err := collection.Find(context.Background(), nil)
        if err != nil {
            log.Fatal(err)
        }
        defer cur.Close(context.Background())
        for cur.Next(context.Background()) {
            raw, err := cur.DecodeBytes()
            if err != nil {
                log.Fatal(err)
            }
            //print element data from collection
            fmt.Println("Element", raw, x)
        }
        if err := cur.Err(); err != nil {
            log.Fatal(err)
        }

I expect it to print out the contents of the collection which are:

_id:5c2d34e36657ba3238374f9a
UID:"ALDK"
PROFILE:"B"
STATUS:"PENDING"
DEVICE:"2.2.2.2"

That is an example entry of the JobBacklog DB.

Full disclosure, the end goal for this is to find the last entry that was added to the collection, but I need to be able to read through the collection first.

I know I'm connected to the DB, I can add/find/delete entries, but the printing out of all in the collection is eluding me. Any assistance is appreciated. Thanks!

  • 写回答

2条回答 默认 最新

  • donmqryh49993 2019-01-04 21:44
    关注

    The error message "document is nil' is about the filter in the Find(). Change the line

    cur, err := collection.Find(context.Background(), nil)

    to

    cur, err := collection.Find(context.Background(), bson.D{{}})

    should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵