文档菜单
文档首页
/ / /
Go 驱动程序
/

检索字段的唯一值

您可以通过使用Distinct() 方法来检索整个集合中字段的唯一值列表。

提示

阅读使用示例 了解如何运行此示例。

以下示例在 movies 集合上执行以下操作

  • 匹配包含 "Natalie Portman" 的 directors 的文档

  • 从匹配的文档中返回 title 的唯一值

coll := client.Database("sample_mflix").Collection("movies")
filter := bson.D{{"directors", "Natalie Portman"}}
// Retrieves the distinct values of the "title" field in documents
// that match the filter
results, err := coll.Distinct(context.TODO(), "title", filter)
// Prints a message if any errors occur during the operation
if err != nil {
panic(err)
}

查看一个可完全运行的示例

运行完整示例后,它返回一个空的 interface 类型切片,包含以下值

A Tale of Love and Darkness
New York, I Love You

要了解更多关于检索唯一值的信息,请参阅 检索唯一值。

Distinct()

返回

计数文档