我在go和mongodb方面都是初学者。我尝试使用bson标签将DocumentResult
解码为结构体,但对于包装字符串的自定义类型无法正常工作。是否可以在不将字段类型更改为字符串的情况下完成?
import (
"context"
"github.com/mongodb/mongo-go-driver/mongo"
)
type MyDoc struct {
SomeInt int `bson:"some_int"`
SomeString string `bson:"some_string,omitempty"`
CustomType MyType `bson:"custom_type,omitempty"`
}
type MyType string
const myType MyType = "ABCD"
func main() {
//Connect to db
client, _ := mongo.Connect(context.Background(), "mongodb://localhost:27017", nil)
db := client.Database("example_db")
collection := db.Collection("col")
//Insert document
docToInsert := MyDoc{42, "The Answer", myType}
collection.InsertOne(nil, docToInsert)
//Retrieve document
filterDoc := MyDoc{SomeInt: 42}
resultDoc := &MyDoc{}
result := collection.FindOne(nil, filterDoc)
result.Decode(resultDoc)
println(resultDoc.SomeInt, resultDoc.SomeString, resultDoc.CustomType)
打印结果:"42 The Answer" //"ABCD"缺失
提前致谢。
UnmarshallBSON
函数来解决了这个问题。然后decode
函数会调用它,在里面定义了一个类似的结构体,只有一个string
,所以我可以将文档解析成它。然后我使用新定义的结构体进行初始化,再进行一些强制类型转换就行了。效果很好。 再次感谢! - amz