5

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

icza
  • 389,944
  • 63
  • 907
  • 827
pidgebob
  • 65
  • 1
  • 4

2 Answers2

5

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, ","))
}
icza
  • 389,944
  • 63
  • 907
  • 827
0

You can use a Setter to use a custom unmarshal method like below:

type Record struct {
    //...
    Groups Groups        `bson:"groups"`
}

type Groups string

func (g *Groups) SetBSON(raw bson.Raw) error {
    var data []string
    err := raw.Unmarshal(&data)
    *g = Groups(strings.Join(data, ","))
    return err
}
hassansin
  • 16,918
  • 3
  • 43
  • 49