mongodb - 如何在 mongodb 中得到 "sort"和 "limit"结果?

标签 mongodb go

我正在尝试使用“排序”和“限制”执行查询。与 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/

相关文章:

javascript - MongoDB : How can I reformat this code to include a sort on the name field?

mongodb - 查询模型的嵌入式列表

javascript - 需要建议 : How to properly connect React to MongoDB

go - 读取 revel app.conf 中的环境变量

go - 为了将 io.Reader 的内容作为字符串指针返回,我可以复制数据的最小次数是多少?

go - Helm : Extra newline when using "include" for templating

java - 与 Mongo 的版本化对象/JSON 映射?

mongodb - MongoDB 中的高可用性

go - 如何在 Golang 中用字符串新建一个对象

sockets - 如何灵活调整套接字数据长度?