如何通过管道函数获取子字段值

I’m writing a code for receiving a data from mongodb in golang.
My code is as below:

type DataContent struct {
    Create time.Time     `bson:"create"`
    Desc   string        `bson:"desc"`
}
type Data struct {
    Id      bson.ObjectId `bson:"_id,omitempty"`
    Desc    string        `bson:"desc"`
    Content DataContent `bson:"content"`
}

func get() error {
    result := []Data{}
    coll := session.DB(“”).C(“aaa”)
    project := bson.M{"$project": bson.M{"_id": 1, "desc": 1, "content": 1 }}
    err := coll.Pipe([]bson.M{project}).All(&result)
    if err != nil {
        return err
    }
    data, err := json.Marshal(result)
    fmt.Printf("#####
%s
#####
", string(data))
    return nil
}

Result of execution is as below:

#####
[{"Id":"58133f92cf4abf18c834750d", "Desc”:”reg1
”,"Content":{"Create":"0001-01-01T00:00:00Z","Desc":""}},
{"Id":"58134bbbcf4abf18c8347513", "Desc”:”reg2
”,”Content":{"Create":"0001-01-01T00:00:00Z","Desc”:””}}]
#####

Values for subfield of “Content” was not come.

I’ve run same process via terminal also. Result is as below:

> db.aaa.aggregate([{$project: { _id:1, desc:1, content:1}}])
[{"Id":"58133f92cf4abf18c834750d", "Desc”:”reg1
”,"Content":{"Create":ISODate("2016-10-28T13:13:13.520Z"),"Desc”:”aaa”}},
{"Id":"58134bbbcf4abf18c8347513", "Desc”:”reg2
”,”Content":{"Create":ISODate("2016-10-28T13:09:32.810Z"),"Desc”:””}}]

Does anyone let me know how to get subfield-value via pipe function?


In addition, “Content” has following structure.

Content : [
 {
    Create : ISODate(“…”),
    Desc : “…”
 },
 {
    Create : ISODate(“…”),
    Desc : “…”
 }
]  

Your Content structure is not a single value but an array of values. This means it cannot be loaded into the field Data.Content which is a single value of type DataContent.

Change your Data.Content field to a slice type ([]DataContent) and it will work:

type Data struct {
    Id      bson.ObjectId `bson:"_id,omitempty"`
    Desc    string        `bson:"desc"`
    Content []DataContent `bson:"content"`
}