dqwr32867 2017-02-07 04:41
浏览 23
已采纳

使用mongodb驱动程序和struct,用大写和小写查找混乱

var Messages []Token
c2 := session.DB("mydatabase").C("pages")
query2 := c2.Find(bson.M{}).All(&Messages)
fmt.Print(Messages)

Here's the structure in my Mongo DB:

id_
pageUrl
token
pageId

I first tried the structure as this:

type Token struct {
    PageUrl string
    Token string
    PageId string
}

but only the token was being printed, perhaps because it's all lowercase. The other two fields were not being retrieved because they contain uppercase. Then I tried this:

type Token struct {
    PageUrl string `json: "pageUrl" bson: "pageUrl"`
    Token string `json: "token" bson: "token"`
    PageId string `json: "pageId" bson: "pageId"`
}    

what are those bson and json things? I've only put it there because I've seen in the internet, but it doesn't work, I still get only the token field

UPDATE with solution and tested example for nested documents

I've seen that there was no posts regarding this question so remember that the solution was to remove the spaces between json: and bson: Also, to help someone who might be wondering how to do it for nested structs, here I give two structures that worked for me:

type Token struct {
    PageUrl string `json:"pageUrl" bson:"pageUrl"`
    Token string `json:"token" bson:"token"`
    PageId string `json:"pageId" bson:"pageId"`
}


type Message struct {
    Sender struct {
        Id string `json:"id" bson:"id"`
    } `json:"sender" bson:"sender"`
    Recipient struct {
        Id string `json:"id" bson:"id"`
    } `json:"recipient" bson:"recipient"`
    Message struct {
        Mid string `json:"mid" bson:"mid"`
        Seq int `json:"seq" bson:"seq"`
        Message string `json:"text" bson:"text"`
    }
}
  • 写回答

1条回答 默认 最新

  • dongshang6062 2017-02-07 06:39
    关注

    these json and bson stuff is called tags

    My best guess is that because Go requires a variable or function to be public by Capitalize the first character, so serialize frameworks like json or bson require the struct Capitalize its first character to expose the field(so that it could see the field). Thus the exposed field name should be defined with a tag (to avoid the restriction).

    the space between bson: and "token" seems to have cause the problem

    I tried following code snippet and seems works fine.

    type Token struct {
        PageUrl string `json:"pageUrl" bson:"pageUrl"`
        Token string `json:"token" bson:"token"`
        PageId string `json:"pageId" bson:"pageId"`
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型