登录
首页 >  Golang >  Go问答

使用 Golang 打印 mongoDB 集合中的所有文档

来源:stackoverflow

时间:2024-03-24 13:18:49 216浏览 收藏

在 Go 中使用 MongoDB 驱动程序打印集合中所有文档时遇到错误“document is nil”,此错误与 `find()` 中的过滤器有关。将 `collection.find(context.background(), nil)` 修改为 `collection.find(context.background(), bson.d{{}})` 应该可以解决此问题。

问题内容

我有一个 mongodb collection collection := db.collection("jobbacklog"),我正在尝试将其打印到控制台中。 db 位于 docker 容器中,并使用 go 编写的脚本对其进行控制。

根据我从 mongo-go-driver https://godoc.org/github.com/mongodb/mongo-go-driver/mongo 找到的内容 有一种方法可以做到这一点,但我的代码不断返回 document is nil 当我知道它不是时。

这是我用来尝试迭代名为 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)
        }

我希望它打印出集合的内容:

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

这是 jobbacklog db 的一个示例条目。

完全公开,最终目标是找到添加到集合中的最后一个条目,但我需要能够首先读取集合。

我知道我已连接到数据库,我可以添加/查找/删除条目,但无法打印出集合中的所有条目。 如有任何帮助,我们将不胜感激。 谢谢!


解决方案


错误消息“document is nil”与 find() 中的过滤器有关。更改行

cur, err := collection.find(context.background(), nil)

cur, err := collection.find(context.background(), bson.d{{}})

应该可以。

db.Collection("JobBacklog").find({},function(err,result){
console.log(result);
})

到这里,我们也就讲完了《使用 Golang 打印 mongoDB 集合中的所有文档》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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