我正在尝试从 go
中的 mongo
并使用 gopkg.in/mgo.v2
获取一些数据。我在 mongo 中有一个嵌套数据。
注意:这是一个旧数据库,我无法更改其结构,只想查询数据。
我有一个包含字段id
、name
和details
的数据库。我必须根据 id
获取详细信息
我的代码:
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Person struct {
Name string
Id string
Details string
}
func main() {
session, err := mgo.Dial("mongodb://localhost:27017/naren")
c := session.DB("naren").C("people")
result := Person{}
err = c.Find(bson.M{"id": "12345"}).One(&result)
if err != nil {
fmt.Println(err)
}
fmt.Println("Details:", result.Details)
fmt.Println("Name:", result.Name)
fmt.Println("Id:", result.Id)
}
Id
和 Name
打印正常,但 result.Details
即使有数据也会打印空字符串。我只想将 json 作为字符串打印或者对 json 数据感到满意。
我也尝试过
...
type Person struct {
...
Details string `json:"details"`
}
但仍然得到空字符串。 提前致谢。
最佳答案
我是个新手。现在这看起来非常基本。键 details
的值为 JSON
解决方法是我将详细信息类型更改为 bson.M
来自
type Person struct {
Name string
Id string
Details string
}
至
type Person struct {
Name string
Id string
Details bson.M
}
现在我可以访问详细信息,例如
res, err := json.Marshal(result.Details)
fmt.Println(string(res))
感谢@putu为我指明了正确的方向。
关于json - 从 go 中的 mongo 获取纯 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485973/