Docs 菜单
Docs 主页
/ / /
Go 驱动程序
/

检索字段的不同值

您可以使用 Distinct() 方法检索集合中某个字段的不同值的列表。

提示

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

以下示例对 movies 集合执行以下操作:

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

  • 从匹配文档中返回 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
var arr []string
err = coll.Distinct(context.TODO(), "title", filter).Decode(&arr)
if err != nil {
panic(err)
}

查看 完全可运行的示例

运行完整示例后,它会打印一个包含以下值的切片:

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

要了解有关检索非重复值的更多信息,请参阅检索非重复值

Distinct()

后退

计算文档