我正在尝试使用“排序”和“限制”执行查询。和mgo https://github.com/go-mgo/mgo你可以做Find(nil).Sort(“-when”).Limit(10)
但是新的官方 mongo 驱动程序 https://godoc.org/github.com/mongodb/mongo-go-driver/mongo没有这样的方法。如何使用新驱动程序进行排序和“限制”?
在当前版本中mongo-go-驱动程序 v1.0.3 https://github.com/mongodb/mongo-go-driver/releases/tag/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 https://godoc.org/go.mongodb.org/mongo-driver/mongo/options。尤其查找选项 https://godoc.org/go.mongodb.org/mongo-driver/mongo/options#FindOptions对于所有可能的选项Find()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)