Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get distinct values in mongodb using golang

Tags:

mongodb

go

mgo

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)

fmt.Println(result)

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

like image 753
manigandand Avatar asked Oct 31 '14 09:10

manigandand


2 Answers

Try this code

 var result []string 

 err = c.Find(nil).Distinct("city", &result)

 if err != nil {
     log.Fatal(err) 
 }

 fmt.Println(result)
like image 136
sanu Avatar answered Oct 19 '22 20:10

sanu


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.

Edit:

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.

like image 44
ANisus Avatar answered Oct 19 '22 22:10

ANisus