Sort Results
On this page
Overview
In this guide, you can learn how to specify the order of your results from read operations.
Sample Data
To run the examples in this guide, load these documents into the
tea.ratings
collection with the following
snippet:
coll := client.Database("tea").Collection("ratings") docs := []interface{}{ bson.D{{"type", "Masala"}, {"rating", 10}}, bson.D{{"type", "Assam"}, {"rating", 5}}, bson.D{{"type", "Oolong"}, {"rating", 7}}, bson.D{{"type", "Earl Grey"}, {"rating", 8}}, bson.D{{"type", "English Breakfast"}, {"rating", 5}}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
Tip
Non-existent 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 rating for a type of tea that corresponds to
the type
and rating
fields.
Note
Each example truncates the ObjectID
value because the driver
generates them uniquely.
Sort Direction
To specify the order of your results, pass an interface specifying the
sort fields and directions to the SetSort()
method of a read
operation's options.
Specify the options as the last parameter to the following read operation methods:
Find()
FindOne()
FindOneAndDelete()
FindOneAndUpdate()
FindOneAndReplace()
gridfs.Bucket.Find()
The sort direction can be ascending or descending.
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 rating
field:
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"rating", 1}}) cursor, err := coll.Find(context.TODO(), filter, opts) var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
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 rating
field:
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"rating", -1}}) cursor, err := coll.Find(context.TODO(), filter, opts) var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
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 the rating
in
the following documents:
[{_id ObjectID("...")} {type Assam} {rating 5}] [{_id ObjectID("...")} {type English Breakfast} {rating 5}]
To guarantee a specific order for documents when ties occur, specify additional fields to sort by.
Example
The following example specifies an ascending sort on the rating
field,
then a descending sort on the type
field:
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"rating", 1}, {"type", -1}}) cursor, err := coll.Find(context.TODO(), filter, opts) var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
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 rating
field, then an ascending sort on the type
field:
sortStage := bson.D{{"$sort", bson.D{{"rating", -1}, {"type", 1}}}} cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage}) if err != nil { panic(err) } var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
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: