2014-10-31 09:59
浏览 41


I tried to retrieve a document from my collection with unique id.

I have a collection with fields: name, age, city, and rank. I want to get 'city' results from mongodb using golang.

My struct code

type exp struct {
    name string `bson:"name"`
    age  int    `bson:"age"`
    city string `bson:"city"`
    rank int    `bson:"rank"`

With the following code to retrieve results from mongodb:

var result []exp //my struct type

err = coll.Find(bson.M{"City":bson.M{}}).Distinct("City",&result)


With this code I get an empty array as the result. How would I get all the cities?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drmeu26880
    drmeu26880 2014-10-31 10:12

    Try this code

     var result []string 
     err = c.Find(nil).Distinct("city", &result)
     if err != nil {
    点赞 评论
  • duangua5308
    duangua5308 2014-10-31 10:04

    Due to restrictions in reflection, mgo (as well as encoding/json and other similar packages) is unable to use unexported fields to marshal or unmarshal data. What you need to do is to export your fields by capitalize the first letter:

    type exp struct {
        Name string `bson:"name"`
        Age  int    `bson:"age"`
        City string `bson:"city"`
        Rank int    `bson:"rank"`

    A side note: you do not need to specify the bson tags if the desired name is the same as the lowercase field name. The documentation for bson states:

    The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag.


    I just realized you did get an empty slice and not a slice with empty struct fields. My answer is then not an actual answer to the question, but it is still an issue that you need to consider.

    点赞 评论