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

huangapple go评论76阅读模式
英文:

How to run Find.().One() in the new go-mongo-driver

问题

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

我想找到一种替代的方法来执行 Find().One()

我尝试了下面的代码,但没有成功:

login := model.LoginModel{}
err := mongo.Collection.Find(bson.M{"name": MAXCOUNT}).Decode(&loginCount)

返回了以下错误:

错误信息无法将类型 []interface {} 转换为 BSON 文档WriteArray 只能在元素或值上进行写入而当前位于顶层

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

我的结构体大致如下:

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

我是否需要相应的 bson 值?

尝试在 go-mongo-driver 中运行 Find().One()。

英文:

Currently we are in the process of migrating the mgo(globalsign) driver to go mongo-driver

And I want some alternative way to do Find.().One()

I tried something like below but it did not help

    login = model.LoginModel{}
    err = mongo.Collection.Find(bson.M{"name": MAXCOUNT}).Decode(&loginCount) 

Returned me back with the below error ,

 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

not sure whether the new Decode method allows a struct value ?

my struct looks something like below


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

}

Do i need to have corresponding bson values too ?

Trying to run Find.().One() in go-mongo-driver

答案1

得分: 2

Collection.Find() 是用于查询多个元素的方法。它返回一个 mongo.Cursor,你可以使用它来迭代结果或使用 Cursor.All() 获取所有结果。

如果你只需要一个结果,可以使用 Collection.FindOne()

例如:

ctx := context.Background() // 使用/设置你的上下文
c := ... // 获取 mongo.Collection

var login model.LoginModel
err = c.FindOne(ctx, bson.M{"name": MAXCOUNT}).Decode(&login)
// 检查错误
英文:

Collection.Find() is designed to query multiple elements. It returns a mongo.Cursor which you can use to iterate over the results or get all using Cursor.All().

If you need a single result, use Collection.FindOne() instead.

For example:

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

huangapple
  • 本文由 发表于 2022年10月28日 20:39:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/74235563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定