dongwan0574 2017-11-26 13:21
浏览 57
已采纳

在Golang中从mongodb检索非结构化数组

I have the following document in MongoDB

{
     "_id" : ObjectId("57e4f8f454b9a4bb13a031d8"),
     "ip" : "192.168.0.1",
     "browser" : "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729)",
     "datetime" : ISODate("2016-09-23T09:42:12.821Z"),
     "userhash" : "BF12742F1B3A486F75E80843230168CE",
     "groups" : [ 
         "group1", 
         "group2"
     ]
}

I'm trying to get the groups into a comma separated string like group1,group2 but as much as I've tried I keep coming up against a brick wall.

Closest I've got is as follows

type Record struct {
    ID           bson.ObjectId `bson:"_id"`
    IP           string        `bson:"ip"`
    Browser      string        `bson:"browser"`
    DateTime     string        `bson:"datetime"`
    Groups       bson.M        `bson:"groups,inline"`
} 

result = []Record{}

_ = c.Find(bson.M{}).All(&result)

The seems to put the groups into a map but I then can't get the groups into a string. I'm fairly new to Go so I'm still learning the different data types and what syntax to use to access them.

Thanks

  • 写回答

2条回答 默认 最新

  • doubi2145 2017-11-27 08:50
    关注

    groups is an array in MongoDB, so in Go use a slice type:

    type Record struct {
        ID           bson.ObjectId `bson:"_id"`
        IP           string        `bson:"ip"`
        Browser      string        `bson:"browser"`
        DateTime     string        `bson:"datetime"`
        Groups       []string      `bson:"groups"`
    }
    

    Once you get the records like this:

    err := c.Find(nil).All(&result)
    // Do check error
    

    You can concatenate them with a comma , using strings.Join(). Example:

    s := []string{"group1", "group2"}
    all := strings.Join(s, ",")
    fmt.Println(all)
    

    The code above prints (try it on the Go Playground):

    group1,group2
    

    So for example to print the groups:

    for _, r := range result {
        fmt.Println(strings.Join(r.Groups, ","))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?