doutui7955 2015-12-27 10:35
浏览 26

使用mgo适配器转到嵌套对象

I'm working on a project that based on MongoDB data structure. Our objects that stored inside the database looks like this:

{
"_id" : ObjectId("567a877df1c7720bea7c2f51"),
"username" : "dog",
"type" : "regular",
"data" : {
    "full" : {
        "xx" : "xx",
        "xx" : "xx",
        "yy" : {
            "xx" : "test"
        },
        "yy" : {
            "xx" : {

            }
        }
    }
}

And the struct that we working on with Golang looks like this:

type User struct {
    Id           bson.ObjectId `bson:"_id,omitempty"`
    username         string
    Type         string
    data struct {
        full struct {
            xx   string   `json:"xx"`
            xx string   `json:"xx"`
            xxx      struct{} `json:"xx"`
            yy    struct {

            } 
        } 
    } 
}

The thing is that the first properties gets fill with data without any problem but the objects inside the object are not working.

Our code to pull data is the regular code as we saw in the MGO documentation.

err = collection.Find(bson.M{"username": username}).One(&user)

Is there any specific way to fetch the data in that way?

  • 写回答

1条回答 默认 最新

  • dounie0889 2015-12-27 13:41
    关注

    I wrote this jus from hand. But You must remember about capitalize name field, and property json form inside structure.

    type User struct {
        Id           bson.ObjectId `bson:"_id,omitempty"`
        Username         string
        Type         string
        Data struct { // Data nor data
            Full struct { // Full nor full
                Xx   string   `json:"xx"`  // Xx nor xx
                Xx string   `json:"xx"`    
                Xxx      struct{} `json:"xx"`
                Yy    struct {   // Yy nor yy
    
                }`json:"yy"` 
            } `json:"full"`
        } `json:"data"`
    }
    

    EDIT:

    Another works example

    Structure in go

    type Event struct{
    
        EvL []struct {
            BaV int     `json:"basicV"`
            ChI int     `json:"chann"`
            DaU int     `json:"dataU"`
    
        } `json:"eventL"`
    
        ST int `json:"send.dat_ts"`
    }
    

    Below how to looks above structure wrote to DB

    { "_id" :
    
        ObjectId("560d422e65f47eef8a118cbd"),
        "evl" :
     [
        {
            "bav" : 255,
            "chi" : 14,
            "dau" : 0,
      ],
      "st" : 5
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度