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

pid*_*bob 5 arrays string go mongodb mgo

我在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"
     ]
}
Run Code Online (Sandbox Code Playgroud)

我试图让这些组成一个逗号分隔的字符串,group1,group2但就像我尝试过的那样,我不断碰到一堵砖墙.

我得到的最近的是如下

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)
Run Code Online (Sandbox Code Playgroud)

似乎将组放入地图但我无法将组变成字符串.我是Go的新手,所以我还在学习不同的数据类型以及用于访问它们的语法.

谢谢

icz*_*cza 5

groups 是 MongoDB 中的数组,因此在 Go 中使用切片类型:

type Record struct {
    ID           bson.ObjectId `bson:"_id"`
    IP           string        `bson:"ip"`
    Browser      string        `bson:"browser"`
    DateTime     string        `bson:"datetime"`
    Groups       []string      `bson:"groups"`
}
Run Code Online (Sandbox Code Playgroud)

一旦你得到这样的记录:

err := c.Find(nil).All(&result)
// Do check error
Run Code Online (Sandbox Code Playgroud)

您可以使用逗号,将它们连接起来strings.Join()。例子:

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

上面的代码打印出来(在Go Playground上试试):

group1,group2
Run Code Online (Sandbox Code Playgroud)

例如打印组:

for _, r := range result {
    fmt.Println(strings.Join(r.Groups, ","))
}
Run Code Online (Sandbox Code Playgroud)