Go nested object with mgo adapter

筅森魡賤 提交于 2019-12-12 03:24:01

问题


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:


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
}


来源:https://stackoverflow.com/questions/34479595/go-nested-object-with-mgo-adapter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!