doudou3716 2016-11-03 06:21 采纳率: 100%
浏览 67

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

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 : “…”
 }
]  
  • 写回答

1条回答 默认 最新

  • douzhe2981 2016-11-03 10:16
    关注

    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"`
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)