go - How can I get unique record from mongodb? -



go - How can I get unique record from mongodb? -

i have collection named 'myplace'. has next fields: place_name, latitude, longitude, city, country.

i want cities start letter "a". tried following:

type place struct{ city string `bson: "city"` }

for retrieving result db:

var city_name []place err = coll.find(bson.m{"city": bson.m{"$regex":"^a", "$options":"si"}}).all(&city_name)

it's getting results. problem of 'myplace' documents have same city, it's returning duplicate city names.

let's have 5 myplaces, 3 city name "baton rouge" , remaining having "trivandrum, kochi". when seek city starting "b", it's returning "baton rouge" 3 times.

how can ensure each city_name unique?

thanks in advance

you can utilize distinct method, in shell :

db.foo.distinct( "city", { "city" : { "$regex" : /^a/i } } );

in go:

var result []string err = c.find( bson.m{"city": bson.m{"$regex":"^a","$options":"si"}} ).distinct("city", &result) if err != nil { log.fatal(err) } fmt.println( result )

mongodb go mongodb-query mgo

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -