如何在mongodb中“排序”和“限制”结果?

mik*_*ike 5 go mongodb

我正在尝试使用“排序”和“限制”执行查询。使用mgo,您可以做到, Find(nil).Sort(“-when”).Limit(10)但是新的正式mongo驱动程序没有这种方法。如何使用新驱动程序进行排序和“限制”?

Wan*_*iar 6

在当前版本的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)
Run Code Online (Sandbox Code Playgroud)

godoc.org/go.mongodb.org/mongo-driver/mongo/options上查看更多可用选项。特别是FindOptions用于的所有可能选项Find()


Mar*_*nto 5

官方驱动程序不像mgo. 您可以使用findopt.Limitand进行排序和限制findopt.Sort

您可以从官方存储库中查看示例。

https://github.com/mongodb/mongo-go-driver/blob/5fea1444e52844a15513c0d9490327b2bd89ed7c/mongo/crud_spec_test.go#L364

  • 不直截了当是轻描淡写。完全是垃圾 (8认同)

Men*_*ndo 5

您可以使用

findOptions := options.Find()
findOptions.SetLimit(2)
findOptions.SetSkip(2)
...
cursor, err := collection.Find(context.Background(), bson.M{}, findOptions)
Run Code Online (Sandbox Code Playgroud)

资源在https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial


jia*_*gli 5

您需要导入“github.com/mongodb/mongo-go-driver/options”包来构建findOptions.

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()
}

Run Code Online (Sandbox Code Playgroud)