问题
Inspecting the interface Cursor in mongo-go-driver:
https://github.com/mongodb/mongo-go-driver/blob/master/mongo/cursor.go#L37
There's no Limit
or Skip
functions.
How can I page the results?
I think I will face the same problem when trying to Sort
or Count
.
Is there a way? or, is this simply not yet implemented in the official driver?
回答1:
Most of the find options you can check in package options
https://github.com/mongodb/mongo-go-driver/tree/master/mongo/options
client, err := mongo.Connect(context.Background(), "mongodb://localhost:27017", nil)
// check err
db := client.Database("examples")
coll := db.Collection("inventory")
{
cursor, err := coll.Find(
context.Background(),
options.SetSort(bson.NewDocument(bson.EC.Int64("x", 1))),
options.SetLimit(30),
options.SetSkip(5),
)
// cursor decode...
}
Count with filter
count, err :=coll.Count(context.Background(),bson.NewDocument(bson.EC.String("foo", "bar")))
Count from document metadata
count, err := coll.EstimatedDocumentCount(context.Background(),countopt.MaxTimeMs(100))
Edit:
Mongo-go-driver stable v1.0.0 released where they separated the BSON library, Please refar to official documentation
来源:https://stackoverflow.com/questions/51956805/how-to-page-a-cursor-in-official-mongo-go-driver