Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

go

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?

like image 252
mike Avatar asked Jul 04 '18 18:07

mike


People also ask

What is the use of sort in MongoDB?

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.


Video Answer


2 Answers

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().

like image 157
Wan Bachtiar Avatar answered Sep 18 '22 05:09

Wan Bachtiar


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

like image 31
Marco Talento Avatar answered Sep 22 '22 05:09

Marco Talento