登录
首页 >  Golang >  Go问答

如何在新的 go-mongo-driver 中运行 Find.().One()

来源:stackoverflow

时间:2024-02-13 13:18:22 289浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《如何在新的 go-mongo-driver 中运行 Find.().One()》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

目前我们正在将 mgo(globalsign) 驱动程序迁移到 go mongo-driver

我想要一些替代方法来执行 find.().one()

我尝试了类似下面的方法,但没有帮助

login = model.loginmodel{}
    err = mongo.collection.find(bson.m{"name": maxcount}).decode(&logincount)

给我返回了以下错误,

error was: cannot transform type []interface {} to a bson document: writearray can only write a array while positioned on a element or value but is positioned on a toplevel

不确定新的 decode 方法是否允许结构体值?

我的结构如下所示

type LoginModel struct {
Username    string  `json:"username"`
Password    string  `json:"password"`

}

我也需要有相应的 bson 值吗?

尝试在 go-mongo-driver 中运行 find.().one()


正确答案


Collection.Find() 旨在查询多个元素。它返回一个 mongo.Cursor,您可以使用它来迭代结果或使用 Cursor.All() 获取所有结果。

如果您需要单个结果,请改用 Collection.FindOne()

例如:

ctx := context.Background() // Use / setup your context
c := ... // acquire mongo.Collection

var login model.LoginModel
err = c.FindOne(ctx, bson.M{"name": MAXCOUNT}).Decode(&login)
// check error

以上就是《如何在新的 go-mongo-driver 中运行 Find.().One()》的详细内容,更多关于的资料请关注golang学习网公众号!

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