0

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?

Daniel Chernenkov
  • 715
  • 1
  • 7
  • 23
  • 2
    You have to export the fields (capitalize them) to be able to marshal data. Use struct tags to map Mongo column names to Go field names. – elithrar Dec 27 '15 at 11:11

1 Answers1

2

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
}
Mbded
  • 1,754
  • 4
  • 23
  • 43