json - 从 go 中的 mongo 获取纯 json

标签 json mongodb go mgo

我正在尝试从 go 中的 mongo 并使用 gopkg.in/mgo.v2 获取一些数据。我在 mongo 中有一个嵌套数据。

注意:这是一个旧数据库,我无法更改其结构,只想查询数据。

我有一个包含字段idnamedetails的数据库。我必须根据 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)
}

IdName 打印正常,但 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/

相关文章:

javascript - jquery: "Exception thrown and not caught"在 IE8 中,但在其他浏览器中有效

java - MongoCursor 没有 count() 方法?

arrays - golang 中的全局数组

javascript - Mongoose/NestJs 无法访问 createdAt,即使 {timestamps : true}

go - 我如何在Go中过滤此输出

docker - 设置 PATH 变量并在 Dockerfile 中获取环境

arrays - 我如何在 golang 中定义这种类型的数据

javascript - 从服务器格式化此 JSON 数据时遇到问题

jquery - 在 Javascript/jQuery 中将纯 JSON 内容打印到 html 页面

mongodb - 如何将 mongo 中的特定查询导出到 csv?