Docs Menu
Docs Home
/ / /
Scala
/

Sorts

On this page

  • Ascending
  • Descending
  • Text Score
  • Combining Sorts

The Sorts class provides static factory methods for the MongoDB sort criteria operators. Each method returns an instance of the Bson type, which can in turn be passed to any method that expects sort criteria.

You can import the methods of the Sorts class statically, as shown in the following code:

import org.mongodb.scala.model.Sorts._

The examples in this guide assume this static import.

To specify an ascending sort, use one of the ascending() methods.

The following example specifies an ascending sort on the quantity field:

ascending("quantity")

The following example specifies an ascending sort on the quantity field, followed by an ascending sort on the totalAmount field:

ascending("quantity", "totalAmount")

To specify a descending sort, use one of the descending() methods.

The following example specifies a descending sort on the quantity field:

descending("quantity")

The following example specifies a descending sort on the quantity field, followed by a descending sort on the totalAmount field:

descending("quantity", "totalAmount")

To specify a sort on the score of a $text query, use the metaTextScore() method to specify the name of the projected field.

The following example specifies a descending sort on the score of a $text query that will be projected into the scoreValue field:

metaTextScore("scoreValue")

To combine multiple sort criteria, use the orderBy() method.

The following example specifies ascending sorts on the quantity and totalAmount fields, followed by a descending sort on the orderDate field:

orderBy(ascending("quantity", "totalAmount"), descending("orderDate"))

Back

Projections