如何从MongoDB中获取唯一记录?

huangapple go评论102阅读模式
英文:

How can I get unique record from mongodb?

问题

我有一个名为'myplace'的集合。它有以下字段:place_name、latitude、longitude、city、country。

我想要以字母"A"开头的所有城市。我尝试了以下代码:

type Place struct{
    City string `bson:"City"`
}

var city_name []Place
err = coll.Find(bson.M{"city": bson.M{"$regex":"^a", "$options":"si"}}).All(&city_name)

它能够获取到所有结果。问题是,一些'myplace'文档中的城市名相同,所以返回了重复的城市名。

假设我有5个'myplace',其中3个城市名为"Baton Rouge",剩下的两个为"Trivandrum, Kochi"。当我尝试获取以字母"B"开头的城市时,它会返回3次"Baton Rouge"。

如何确保每个城市名都是唯一的呢?

提前感谢。

英文:

I have a collection named 'myplace'. It has the following fields: place_name, latitude, longitude, city, country.

I want all the cities that start with the letter "A". I tried the following:

type Place struct{
    City string `bson: "City"`
}

For retrieving the result from the db:

var city_name []Place
err = coll.Find(bson.M{"city": bson.M{"$regex":"^a", "$options":"si"}}).All(&city_name)

It's getting all the results. The problem is that some of the 'myplace' documents have the same city, so it's returning duplicate city names.

Let's say I have 5 myplaces, 3 with the city name "Baton Rouge" and remaining having "Trivandrum, Kochi". When I try to get the city starting with "B", it's returning "Baton Rouge" 3 times.

How can I ensure each city_name is unique?

Thanks in advance

答案1

得分: 1

你可以使用Distinct方法,在shell中的写法如下:

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

在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)
英文:

You can use the Distinct method, in the shell it will look like :

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 )

答案2

得分: 0

你可以使用Distinct方法来实现:

err = coll.Find(bson.M{"city": bson.M{"$regex":"^a", "$options":"si"}}).Distinct("city", &city_name)

..这里假设city_name实际上是一个切片。

英文:

You can use Distinct:

err = coll.Find(bson.M{"city": bson.M{"$regex":"^a", "$options":"si"}}).Distinct("city", &city_name)

..this assumes that city_name is actually a slice.

huangapple
  • 本文由 发表于 2014年10月29日 17:48:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/26627101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定