如何在MongoDB中进行“排序”和“限制”结果?

15

我正在尝试使用“sort”和“limit”执行查询。在mgo中,您可以这样做:Find(nil).Sort(“-when”).Limit(10),但是新的、官方的mongo驱动程序没有这些方法。如何使用新驱动程序进行排序和“limit”操作?


2
大概可以使用findopt.Sort来构建Find的选项。不幸的是,它需要一个interface{}参数,文档没有提供任何有用的信息,并且文档或GitHub中也没有示例。 - mu is too short
6个回答

27
在当前版本 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上可以查看更多可用选项。特别是Find()的所有可能选项的FindOptions


5

8
不坦率简直是个轻描淡写。这完全是胡说八道。 - mike
1
这个已经过时了,请使用options.Find()代替。 - pixeloverflow

5

要构建 findOptions,您需要导入 "github.com/mongodb/mongo-go-driver/options" 包。

import github.com/mongodb/mongo-go-driver/options

findOptions := options.Find() // build a `findOptions`
findOptions.SetSort(map[string]int{"when": -1}) // reverse order by `when`
findOptions.SetSkip(0) // skip whatever you want, like `offset` clause in mysql
findOptions.SetLimit(10) // like `limit` clause in mysql

// apply findOptions
cur, err := collection.Find(context.TODO(), bson.D{}, findOptions)
// resolve err

for cur.Next(context.TODO()) {
   // call cur.Decode()
}


5

3

显然,sort选项要求您添加一个map[string]interface{},在其中您可以将字段指定为键,并将排序顺序指定为值(其中1表示升序,-1表示降序),如下所示:

sortMap := make(map[string]interface{})
sortMap["version"] = 1
opt := findopt.Sort(sortMap)

据我所见,这意味着您只能通过一个 sortField 正确地对结果进行排序,因为 go map 中的键是随机存储的。

3

一行选项

我知道已经有很多答案了,但你可以将其缩减为一行(如果你需要在任何情况下使用它)

// From the Doc
// func (f *FindOptions) SetSort(sort interface{}) *FindOptions

cursor, err := collection.Find(context.Background(), bson.M{}, options.Find().SetSort(map[string]int{"when": -1}).SetLimit(10))

SetSort()和其他函数当前返回其父指针本身。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接