I'm trying to execute a query with "sort" and "limit". With mgo you could do Find(nil).Sort(“-when”).Limit(10)
but the new, official mongo driver has no such methods. How can I sort and "limit" with the new driver?
MongoDB – sort() Method The sort() method specifies the order in which the query returns the matching documents from the given collection. You must apply this method to the cursor before retrieving any documents from the database.
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()
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With