dongwan0574
2017-11-26 13:21
浏览 55

在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, ","))
    }
    
    点赞 打赏 评论
  • duanchun1909 2017-11-26 23:34

    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
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题