How to "sort" and "limit" results in mongodb?

The official driver is not straightforward as mgo. You can do sort and limit using the findopt.Limit and findopt.Sort.

You can see examples from the official repository.

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


In the current version mongo-go-driver v1.0.3, the options are simplified. For example to perform find, sort and limit:

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)

See more available options on godoc.org/go.mongodb.org/mongo-driver/mongo/options. Especially FindOptions for all possible options for Find().

Tags:

Mongodb

Go