File: sorts.md

package info (click to toggle)
mongo-java-driver 3.6.3-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 16,112 kB
  • sloc: java: 102,506; xml: 395; sh: 43; makefile: 4
file content (79 lines) | stat: -rw-r--r-- 2,183 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
+++
date = "2015-03-19T14:27:51-04:00"
title = "Sort Criteria  "
[menu.main]
  parent = "Builders"
  weight = 30
  pre = "<i class='fa'></i>"
+++

## Sorts

The [`Sorts`]({{< apiref "com/mongodb/client/model/Sorts" >}}) class provides static factory methods for all the MongoDB sort criteria 
operators.  Each method returns an instance of the [`Bson`]({{< relref "bson/documents.md#bson" >}}) type, which can in turn be passed to
any method that expects sort criteria.

For brevity, you may choose to import the methods of the `Sorts` class statically:

```java
import static com.mongodb.client.model.Sorts.*;
```
  
All the examples below assume this static import.

### Ascending

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

This example specifies an ascending sort on the `quantity` field:

```java
ascending("quantity")
```

This example specifies an ascending sort on the `quantity` field, followed by an ascending sort on the `totalAmount` field:

```java
ascending("quantity", "totalAmount") 
```

### Descending

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

This example specifies a descending sort on the `quantity` field:

```java
descending("quantity")
```

This example specifies a descending sort on the `quantity` field, followed by a descending sort on the `totalAmount` field:


```java
descending("quantity", "totalAmount") 
```

### Text Score

To specify a sort by [the score of a `$text` query]({{< docsref "reference/operator/query/text/#sort-by-text-search-score" >}}), use the 
`metaTextScore` method to specify the name of the projected field.

This example specifies a sort on the score of a `$text` query that will be projected into the `scoreValue` field in a projection on the 
same query:

```java
metaTextScore("scoreValue")
```

### Combining sort criteria

To specify the combination of multiple sort criteria, use the `orderBy` method.

This example specifies an ascending sort on the `quantity` field, followed by an ascending sort on the `totalAmount` field, followed by a 
descending sort on the `orderDate` field:

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