如何使用 go mongo 驱动程序一起执行查找、区分和排序

Posted

技术标签:

【中文标题】如何使用 go mongo 驱动程序一起执行查找、区分和排序【英文标题】:How to perform Find, Distinct & Sort all together using go mongo driver 【发布时间】:2020-11-17 16:41:14 【问题描述】:

我有一个使用"labix.org/v2/mgo" library 生成的命令

err = getCollection.Find(bson.M).Sort("department").Distinct("department", &listedDepartment)

这工作正常。但是现在我正在转向官方的 golang mongo-driver "go.mongodb.org/mongo-driver/mongo" 并且我想在那个库中运行这个命令,但是我没有可以使用 Find then Sort then Distinct 的直接函数。如何使用这个 mongo-driver 来实现这个命令。变量listedDepartment 的类型为[]string。请建议我知道解决方案。

【问题讨论】:

【参考方案1】:

你可以使用Collection.Distinct(),但它还不支持排序:

// Obtain collection:
c := client.Database("dbname").Collection("collname")

ctx := context.Background()
results, err := c.Distinct(ctx, "department", bson.M)

它返回一个[]interface 类型的值。如果您知道它包含 string 值,则可以使用循环并键入断言来获取字符串值,如下所示:

listedDepartment = make([]string, len(results))
for i, v := range results 
    listedDepartment[i] = v.(string)

如果您需要对其进行排序,只需对切片进行排序:

sort.Strings(listedDepartment)

【讨论】:

以上是关于如何使用 go mongo 驱动程序一起执行查找、区分和排序的主要内容,如果未能解决你的问题,请参考以下文章