Sort Results
On this page
Overview
In this guide, you can learn how to specify the order of your results from an operation.
Sample Data
The examples in this guide use the following Course
struct as a model for documents
in the courses
collection:
type Course struct { Title string Enrollment int32 }
To run the examples in this guide, load the sample data into the
db.courses
collection with the following snippet:
coll := client.Database("db").Collection("courses") docs := []interface{}{ Course{Title: "World Fiction", Enrollment: 35}, Course{Title: "Abstract Algebra", Enrollment: 60}, Course{Title: "Modern Poetry", Enrollment: 12}, Course{Title: "Plate Tectonics", Enrollment: 35}, } result, err := coll.InsertMany(context.TODO(), docs)
Tip
Nonexistent Databases and Collections
If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.
Each document contains a description of a university course that
includes the course title and maximum enrollment, corresponding to
the title
and enrollment
fields in each document.
Sort Direction
To specify the order of your results, pass an interface specifying the
sort fields and direction to the SetSort()
method of an operation's options.
The following operations take options as a parameter:
Find()
FindOne()
FindOneAndDelete()
FindOneAndUpdate()
FindOneAndReplace()
gridfs.Bucket.Find()
You can set an ascending or descending sort direction.
Ascending
An ascending sort orders your results from smallest to largest. To
specify this sort, pass the field you want to sort by and 1
to the
SetSort()
method.
Tip
With an ascending sort, the method orders values of type
Boolean
from false
to true
, String
type values
from a to z and numeric type values from negative infinity to
positive infinity.
Example
The following example specifies an ascending sort on the enrollment
field:
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"enrollment", 1}}) cursor, err := coll.Find(context.TODO(), filter, opts) var results []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) }
Descending
A descending sort orders your results from largest to smallest. To
specify this sort, pass the field you want to sort by and -1
to the
SetSort()
method.
Tip
With an descending sort, the method orders values of type
Boolean
from true
to false
, String
type values
from z to a and numeric type values from positive infinity to
negative infinity.
Example
The following example specifies a descending sort on the enrollment
field:
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"enrollment", -1}}) cursor, err := coll.Find(context.TODO(), filter, opts) var results []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) }
Handling Ties
A tie occurs when two or more documents have identical values in the field you are using to sort your results. MongoDB does not guarantee order if ties occur.
For example, in the sample data, there is a tie for enrollment
in
the following documents:
{"title":"World Fiction","enrollment":35} {"title":"Plate Tectonics","enrollment":35}
You can sort on additional fields to resolve ties in the original sort. If you want to guarantee a specific order for documents, select sort fields that do not result in ties.
Example
The following example specifies a descending sort on the enrollment
field,
then an ascending sort on the title
field:
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"enrollment", -1}, {"title", 1}}) cursor, err := coll.Find(context.TODO(), filter, opts) var results []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) }
Aggregation
You can also include the $sort stage to specify a sort in an aggregation pipeline.
Example
The following example specifies a descending sort on the enrollment
field, then an ascending sort on the title
field:
sortStage := bson.D{{"$sort", bson.D{{"enrollment", -1}, {"title", 1}}}} cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage}) if err != nil { panic(err) } var results []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) }
Additional Information
To learn more about the operations mentioned, see the following guides:
To learn about sorting text scores from your text search, see Search Text.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: