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
CodePudding user response:
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