登录
首页 >  Golang >  Go问答

努力将 MongoDB singleResult 对象转换为 Go 结构

来源:stackoverflow

时间:2024-03-17 12:36:28 114浏览 收藏

在使用 MongoDB 的 Go 驱动程序时,将单一结果对象转换为 Go 结构会遇到问题。尝试按照文档进行操作后仍然无法成功。最终发现,将结构中的标签从“json”更改为“bson”解决了问题。

问题内容

我尝试按照此处和此处的文档进行操作,但没有成功。

i want to get a singleresult from findone on the collection named moviescollection and then use decode or unmarshal to put those values into a struct. struct jsondata 中的值与每个 document 中的值完全相同

我使用的是官方 mongodb 驱动程序 github.com/mongodb/mongo-go-driver

这是我尝试过的示例:

mongocontext, cancelcontext := context.withtimeout(context.background(), 10*time.second)

defer cancelcontext()

mongoclient, _ := mongo.connect(mongocontext, options.client().applyuri("mongodb://localhost:27017"))
moviescollection := mongoclient.database("entertainment").collection("movies")

moviescollection.insertone(mongocontext, bson.m{"_id": "deadpool", "path": "path/to/file"})

singleresult := moviescollection.findone(mongocontext, bson.m{"_id": "deadpool"})

if singleresult.err() != nil {
    log.println("find error: ", singleresult.err())
}

jsondata := struct {
    path string `json:"path"`
}{}

decodeerror := singleresult.decode(&jsondata)

if decodeerror != nil {
    log.println("decode error: ", decodeerror)
}

fmt.println("path: ", jsondata.path)

但是不会产生任何错误,并且 json.path 会产生空字符串。

我还尝试使用 bson.d{{"_id", "deadpool"}} 而不是 bson.m{"_id": "deadpool"}

我可以确认 json.path 不是空字符串,因为我已经使用 mongodb compass 本机检查了数据库。 该条目包含以下内容:

{"_id":"Deadpool","Path":"path/to/file"}

解决方案


在内部,mongodb 使用bson。按如下方式更改您的结构应该可行。

来自

jsondata := struct {
    path string `json:"path"`
}{}

jsondata := struct {
    path string `bson:"path"`
}{}

嘿,正如 simagix 提到的,您应该能够将标签从 json 更改为 bson:

`bson:"path"`

如果您需要获得更通用的结果,另一种选择是向其传递一个 d 对象,如下所示:

JSONData := &bson.D{}
decodeError := singleResult.Decode(JSONData)

然后您可以使用 json.data.map 函数通过地图获取所有信息。

今天关于《努力将 MongoDB singleResult 对象转换为 Go 结构》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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