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"`
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应