Skip to content

Instantly share code, notes, and snippets.

@tgrall
Created October 29, 2014 10:37
Show Gist options
  • Save tgrall/664f2070120ca3efb9af to your computer and use it in GitHub Desktop.
Save tgrall/664f2070120ca3efb9af to your computer and use it in GitHub Desktop.
Go Sample : How to do a Distinct
package main
import (
"fmt"
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type City struct {
Name string
Zip int
State string
}
func main() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("demo").C("cities")
err = c.DropCollection()
err = c.Insert(
&City{"Aberdeen", 57401, "SD"},
&City{"Aberdeen", 57402, "SD"},
&City{"Austin", 78701, "TX"},
&City{"Austin", 78702, "TX"},
&City{"Austin", 78703, "TX"},
&City{"Austin", 78704, "TX"},
&City{"Austin", 78705, "TX"},
&City{"Anchorage", 99501, "AL"},
&City{"Anchorage", 99521, "AL"},
&City{"Anchorage", 99524, "AL"},
&City{"Montpelier", 83254, "ID"},
&City{"Springfield", 62701, "IL"},
&City{"Springfield", 62702, "IL"},
&City{"Springfield", 62703, "IL"},
&City{"Springfield", 62704, "IL"},
&City{"Indianapolis", 46201, "IN"})
if err != nil {
log.Fatal(err)
}
// Query Distinct
var result []string
err = c.Find( bson.M{"name": bson.M{"$regex":"^A", "$options":"si"}} ).Distinct("name", &result)
if err != nil {
log.Fatal(err)
}
fmt.Println( result )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment