Overview
在本指南中,您可以了解如何在单个集合中检索指定字段的不同值。
样本数据
本指南中的示例将以下 Course
结构作为 courses
集合中的文档的模型:
type Course struct { Title string Department string Enrollment int32 }
要运行该示例,请使用以下代码段将示例数据加载到db.courses
集合中:
coll := client.Database("db").Collection("courses") docs := []interface{}{ Course{Title: "World Fiction", Department: "English", Enrollment: 35}, Course{Title: "Abstract Algebra", Department: "Mathematics", Enrollment: 60}, Course{Title: "Modern Poetry", Department: "English", Enrollment: 12}, Course{Title: "Plate Tectonics", Department: "Geology", Enrollment: 30}, } result, err := coll.InsertMany(context.TODO(), docs)
提示
不存在的数据库和集合
如果执行写操作时不存在必要的数据库和集合,服务器会隐式创建这些数据库和集合。
每个文档都包含大学课程的说明,其中包括课程标题、部门和注册人数。 这些项目对应于每个文档中的title
、 department
和enrollment
字段。
distinct
要在单个collection中检索指定字段的不同值,请将以下参数传递给Distinct()
方法:
要检索其非重复值的字段名称
non-nil
查询筛选器,指定要匹配的文档
提示
如果指定空查询筛选器,则Distinct()
方法会在collection中的所有文档中搜索不同值。
修改行为
您可以通过传入 DistinctOptions
来修改 Distinct()
方法的行为。如果不指定 DistinctOptions
,则驱动程序将使用每个选项的默认值。
DistinctOptions
类型允许您使用以下方法配置选项:
方法 | 说明 |
---|---|
| The type of language collation to use when sorting results. Default: nil |
| Sets a comment to attach to the distinct operation. Default: nil |
例子
以下示例匹配 enrollment
字段值小于 50
的文档,并使用 Distinct()
方法打印 department
字段的不同值:
filter := bson.D{{"enrollment", bson.D{{"$lt", 50}}}} var arr []string err = coll.Distinct(context.TODO(), "department", filter).Decode(&arr) if err != nil { panic(err) } fmt.Printf("%s\n", arr)
[English Geology]
检索不同值示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用 Atlas示例数据集包含的 sample_restaurants
数据库中的 restaurants
集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下示例对 restaurant
集合执行以下操作:
匹配
cuisine
字段值为"Tapas"
的文档从匹配文档中返回
borough
字段的不同值
// Retrieves distinct values of a field by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{} } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/zh-cn/docs/drivers/go/current/usage-examples/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() // Filters the collection for documents where the value of cuisine is "Tapas" coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"cuisine", "Tapas"}} // Retrieves the distinct values of the "borough" field in documents // that match the filter var arr []string err = coll.Distinct(context.TODO(), "borough", filter).Decode(&arr) if err != nil { panic(err) } // Prints the distinct "borough" values for _, result := range arr { fmt.Println(result) } // When you run this file, it should print: // Brooklyn // Manhattan // Queens }
Brooklyn Manhattan Queens
更多信息
要了解如何构建查询筛选器,请参阅指定查询。
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: