我正在尝试使用“排序”和“限制”执行查询。与 mgo你可以做 Find(nil).Sort(“-when”).Limit(10)
但 new, official mongo driver没有这样的方法。如何使用新驱动程序进行排序和“限制”?
最佳答案
在当前版本中 mongo-go-driver v1.0.3 ,选项被简化。例如执行查找、排序和限制:
import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
options := options.Find()
// Sort by `_id` field descending
options.SetSort(bson.D{{"_id", -1}})
// Limit by 10 documents only
options.SetLimit(10)
cursor, err := collection.Find(context.Background(), bson.D{}, options)
在 godoc.org/go.mongodb.org/mongo-driver/mongo/options 上查看更多可用选项.特别是FindOptions Find()
的所有可能选项。
关于mongodb - 如何在 mongodb 中得到 "sort"和 "limit"结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51179588/