1

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?

rsan
  • 1,887
  • 2
  • 17
  • 23

1 Answers1

7

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

M Ashraful A
  • 627
  • 6
  • 13
  • Thanks @M Ashraf ul A there's no examples of those methods in the official documentation! But I should have pick a little more in the source code. Maybe I could have find those functions. Thanks again. – rsan Sep 21 '18 at 22:18
  • can you please provide a link to the package? Thanks! – rrw Nov 26 '18 at 06:34
  • 1
    @rrw in latest beta release package `findopt` become `options` https://github.com/mongodb/mongo-go-driver/blob/master/mongo/options/findoptions.go – M Ashraful A Nov 26 '18 at 08:04
  • no longer works, it shows: type *mongo.Collection has no field or method Count. renamed to CountDocuments – James Tan Apr 03 '19 at 09:44