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条)

报告相同问题?

悬赏问题

  • ¥15 求红米或者任意工作安卓机ro,ot之后劫c ,h ,i摄像头, 实现无人直播瞒过抖音直播助手的教程, 或者远程 协助也可以。
  • ¥15 elasticsearch
  • ¥30 python ttk 获取下拉框问题
  • ¥15 uniapp的uni-datetime-picker组件在ios端不适配
  • ¥15 前端 uniapp App端在离线状态如何使用modbus 连接手机蓝牙进行读写操控机器?
  • ¥15 SQL语句根据字段自动生成行
  • ¥500 “掌声响起来”软件(不确定性人工智能)
  • ¥500 我要找大模型一体机产品手册和应用案例
  • ¥20 关于游戏c++语言代码问题
  • ¥15 如何制作永久二维码,最好是微信也可以扫开的。(相关搜索:管理系统)