How to page a cursor in official mongo-go-driver

落爺英雄遲暮 提交于 2019-12-02 17:45:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!