Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve unstructured array from mongodb in golang

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

like image 245
pidgebob Avatar asked Nov 26 '17 13:11

pidgebob


1 Answers

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, ","))
}
like image 73
icza Avatar answered Nov 14 '22 02:11

icza