Docs Menu
Docs Home
/
MongoDB Atlas
/ /

How to Sort Your Atlas Search Results

On this page

  • Load the Sample Data
  • Overview
  • Procedure
  • Create the Atlas Search Index
  • Overview
  • Procedure
  • Sort Your Search Results
  • Sort Numbers
  • Sort Dates
  • Sort Strings

This tutorial describes how to sort the Atlas Search results by numeric, date, and string fields in the sample_mflix.movies collection in ascending or descending order. It also demonstrates how to perform a case-insensitive sort of your Atlas Search results. When you create an Atlas Search index on a collection, you can configure the index to normalize the value of a string field to lowercase. This allows you to sort your query results regardless of the sorted field's letter case.

To demonstrate how to sort Atlas Search results by numeric, date, and string fields using the default behavior of Atlas Search sort option, the tutorial takes you through the following steps:

  1. Create an Atlas Search index on the string field named title, date field named released, and numeric field named awards.wins in the sample_mflix.movies collection for both running queries against these fields and sorting the results by these fields.

    Note

    If you enable dynamic mappings, Atlas Search automatically indexes number and date types for sorting. It doesn't dynamically index string fields for sorting. Instead, you must use the token type to index string fields for sorting.

  2. Run Atlas Search queries against the title, released, and awards.wins fields in the sample_mflix.movies collection and sort the results in ascending and descending order by these fields.

To demonstrate how to sort Atlas Search results by normalizing the value of a string field to lowercase using Atlas Search sort option, the tutorial takes you through the following steps:

  1. Load sample documents into the sample_mflix.movies collection on your Atlas cluster.

  2. Create Atlas Search indexes on the string field named title for both running queries and sorting the results by this field.

    Note

    If you enable dynamic mappings, Atlas Search automatically indexes number and date types for sorting. It doesn't dynamically index string fields for sorting. Instead, you must use the token type to index string fields for sorting.

  3. Run Atlas Search queries against the title field in the collection and sort the results by the indexed fields.

Before you begin, ensure that your Atlas cluster meets the requirements described in the Prerequisites.

To create an Atlas Search index, you must have Project Data Access Admin or higher access to the project.

To sort documents in the sample_mflix.movies collection by number, date, and string fields using the default sort behavior, you can skip this section and proceed to create the index for the collection.

To demonstrate how Atlas Search sorts documents regardless of the letter case, we provide sample documents. Each sample document represents a movie and contains three fields that specifies the movie's title (in lowercase), genre, and number of awards. In this section, you load the sample documents to the sample_mflix.movies collection in your Atlas cluster. You can load the sample collection using the Atlas UI or mongosh.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

Click the Browse Collections button for your cluster.

The Data Explorer displays.

3

You can load the collection from your Atlas UI or mongosh:

  1. Expand the sample_mflix database and select the movies collection.

  2. For each of the sample document to add to the collection, do the following:

    1. Click Insert Document and select the JSON view ({}) to replace the default document.

    2. One at a time, copy and paste the following sample documents and click Insert to add each document to the collection.

    1{
    2 "genres": [ "Action", "Drama", "Thriller" ],
    3 "title": "atomic train",
    4 "awards": { "wins": 1, "nominations": 1 }
    5}
    1{
    2 "genres": [ "Animation", "Adventure", "Family" ],
    3 "title": "how to train your dragon",
    4 "awards": { "wins": 32, "nominations": 51 }
    5}
  1. Click Connect for the cluster to which you want to connect.

  2. Select Shell and complete the steps to connect to your cluster through mongosh.

    To learn more, see Connect via mongosh.

  3. Switch to the sample_mflix database in mongosh.

    use sample_mflix
    switched to db sample_mflix
  4. Run the following command in mongosh to load the collection to the selected database:

    1db.movies.insertMany([
    2 {
    3 "_id": 1,
    4 "genres": [ "Action", "Drama", "Thriller" ],
    5 "title": "atomic train",
    6 "awards": { wins: 1, nominations: 1 }
    7 },
    8 {
    9 "_id": 2,
    10 "genres": [ "Animation", "Adventure", "Family" ],
    11 "title": "how to train your dragon",
    12 "awards": { "wins": 32, "nominations": 51 },
    13 }
    14])
    { acknowledged: true, insertedIds: { '0': 1, '1': 2 } }

In this section, you will create an Atlas Search index on the title, released, and awards.wins fields in the sample_mflix.movies collection for running queries against these fields and sorting the results by these fields.

In this section, you will create an Atlas Search index on the title field in the sample_mflix.movies collection for running queries against this field and sorting the results by this field.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
4
  • For a guided experience, select the Atlas Search Visual Editor.

  • To edit the raw index definition, select the Atlas Search JSON Editor.

5
  1. In the Index Name field, enter sort-tutorial.

    If you name your index default, you don't need to specify an index parameter in the $search pipeline stage. If you give a custom name to your index, you must specify this name in the index parameter.

  2. In the Database and Collection section, find the sample_mflix database, and select the movies collection.

6

The following index definition:

  • Indexes the awards.wins field as the number type for both querying and sorting the results by the field.

  • Indexes the released field as the date type for both querying and sorting the results by the field.

  • Specifies the keyword analyzer for both indexing and searching the title field, and indexes the title field as the following types:

    • string type for querying the field.

    • token type for sorting the results by the field.

    You can use the Atlas Search Visual Editor or the Atlas Search JSON Editor in the Atlas UI to create the index.

  1. Click Next.

  2. Click Refine Your Index.

  3. In the Index Configurations section, toggle to disable Dynamic Mapping.

  4. In the Field Mappings section, click Add Field to display the Add Field Mapping window.

  5. Click Customized Configuration.

  6. For the following fields, one at a time, select the field name and data type from the corresponding dropdowns, configure the properties if any or accept default, and click Add.

    Field Name
    Data Type
    Properties
    awards.wins
    Number
    Accept default.
    released
    Date
    Accept default.
    title
    Token
    Accept default.
    title
    String
    Select lucene.keyword from both the Index Analyzer and Search Analyzer dropdowns.
  1. Replace the default index definition with the following definition.

    {
    "mappings": {
    "dynamic": false,
    "fields": {
    "awards": {
    "dynamic": false,
    "fields": {
    "wins": [
    {
    "type": "number"
    }
    ]
    },
    "type": "document"
    },
    "released": [
    {
    "type": "date"
    }
    ],
    "title": [{
    "type": "token"
    }, {
    "type": "string",
    "analyzer": "lucene.keyword",
    "searchAnalyzer": "lucene.keyword"
    }]
    }
    }
    }
  2. Click Next.

7
8

A modal window appears to let you know your index is building. Click the Close button.

9

The index should take about one minute to build. While it is building, the Status column reads Build in Progress. When it is finished building, the Status column reads Active.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2
3
  • For a guided experience, select the Atlas Search Visual Editor.

  • To edit the raw index definition, select the Atlas Search JSON Editor.

4
  1. In the Index Name field, enter case-insensitive-sort.

    If you name your index default, you don't need to specify an index parameter in the $search pipeline stage. If you give a custom name to your index, you must specify this name in the index parameter.

  2. In the Database and Collection section, find the sample_mflix database, and select the movies collection.

5

The following index definition indexes the title field as the following types:

  • token type for sorting, which uses the lowercase normalizer to convert the indexed term to lowercase.

  • string type for querying the field.

You can use the Atlas Search Visual Editor or the Atlas Search JSON Editor in the Atlas user interface to create the index.

  1. Click Next.

  2. Click Refine Your Index.

  3. In the Index Configurations section, toggle to disable Dynamic Mapping.

  4. In the Field Mappings section, click Add Field to display the Add Field Mapping window.

  5. Click Customized Configuration.

  6. Select title from the Field Name dropdown.

  7. Select Token from the Data Type dropdown.

  8. Expand Token Properties and select lowercase from the Normalizer dropdown.

  9. Click Add.

  10. Repeat steps d and e.

  11. Select String from the Data Type dropdown.

  12. Click Add.

  1. Replace the default index definition with the following definition.

    1{
    2 "mappings": {
    3 "dynamic": false,
    4 "fields": {
    5 "title": [{
    6 "type": "token",
    7 "normalizer": "lowercase"
    8 },{
    9 "type": "string"
    10 }]
    11 }
    12 }
    13}
  2. Click Next.

6

A modal window displays to let you know that your index is building.

7

The index should take about one minute to build. While it is building, the Status column reads Initial Sync. When it is finished building, the Status column reads Active.


Use the Select your language drop-down menu to set the language of the example in this section.


You can sort your search results in multiple ways. In this section, you connect to your Atlas cluster and then run the sample queries against the indexed fields in the sample_mflix.movies collection.

The $search stage in the sample queries use the sort option to sort the Atlas Search results by the indexed number field.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

Click the Query button to the right of the index to query.

4

Click Edit Query to view a default query syntax sample in JSON format.

5

The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

[
{
"$search": {
"index": "sort-tutorial",
"range": {
"path": "awards.wins",
"gte": 10
},
"sort": {
"awards.wins": -1,
}
}
}
]
SCORE: 1 _id: "573a13d5f29313caabd9cae7"
fullplot: "Based on an incredible true story of one man's fight for survival and …"
imdb: Object
...
year: 2013
...
awards: Object
wins: 267
...
...
SCORE: 1 _id: "573a13c7f29313caabd74a4d"
fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…"
imdb: Object
...
year: 2013
...
awards: Object
wins: 231
...
...
SCORE: 1 _id: "573a13cbf29313caabd808d2"
fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…"
imdb: Object
...
year: 2013
...
awards: Object
wins: 231
...
...
SCORE: 1 _id: “573a13dff29313caabdb7adb”"
fullplot: "Actor Riggan Thomson is most famous for his movie role from over twent…"
imdb: Object
...
year: 2014
...
awards: Object
wins: 210
...
...
SCORE: 1 _id: "573a13bef29313caabd5c06c"
plot: "The life of Mason, from early childhood to his arrival at college."
imdb: Object
...
runtime: 165
...
awards: Object
wins: 185
...
...
SCORE: 1 _id: "573a139ef29313caabcfbd6a"
fullplot: "While Frodo & Sam continue to approach Mount Doom to destroy the One R…"
imdb: Object
...
year: 2003
...
awards: Object
wins: 175
...
...
SCORE: 1 _id: "573a13b5f29313caabd447f5"
plot: "In rural Texas, welder and hunter Llewelyn Moss discovers the remains …"
imdb: Object
...
year: 2007
...
awards: Object
wins: 172
...
...
SCORE: 1 _id: "573a13c3f29313caabd68d9f"
plot: "On a fall night in 2003, Harvard undergrad and computer programming ge…"
imdb: Object
...
year: 2010
...
awards: Object
wins: 171
...
...
SCORE: 1 _id: "573a13c5f29313caabd6ee61"
fullplot: "Dom Cobb is a skilled thief, the absolute best in the dangerous art of…"
imdb: Object
...
year: 2010
...
awards: Object
wins: 162
...
...
SCORE: 1 _id: "573a13bdf29313caabd58fd3"
plot: "The story of Jamal Malik, an 18 year-old orphan from the slums of Mumb…"
imdb: Object
...
year: 2008
...
awards: Object
wins: 161
...
...
6

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

1

Open mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see Connect via mongosh.

2

Run the following command at mongosh prompt:

use sample_mflix
3

The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

The query uses the following pipeline stages:

  • $search stage to search the awards.wins field and sort the results in descending order.

  • $limit stage to limit the output to 5 results.

  • $project stage to exclude all fields except title and awards.wins.

1db.movies.aggregate([
2 {
3 "$search": {
4 "index": "sort-tutorial",
5 "range": {
6 "path": "awards.wins",
7 "gte": 10
8 },
9 "sort": {
10 "awards.wins": -1,
11 }
12 }
13 },
14 {
15 $limit: 5
16 },
17 {
18 "$project": {
19 "_id": 0,
20 "title": 1,
21 "awards.wins": 1
22 }
23 }
24])
[
{
title: '12 Years a Slave',
awards: { wins: 267 }
},
{
title: 'Gravity',
awards: { wins: 231 }
},
{
title: 'Gravity',
awards: { wins: 231 }
},
{
title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
awards: { wins: 210 }
},
{
title: 'Boyhood',
awards: { wins: 185 }
}
]
1

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.

2

On the Database screen, click the sample_mflix database, then click the movies collection.

3

The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

The query uses the following pipeline stages:

  • $search stage to search the awards.wins field and sort the results in descending order.

  • $limit stage to limit the output to 5 results.

  • $project stage to exclude all fields except title and awards.wins.

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.

    Pipeline Stage
    Query
    $search
    {
    index: "sort-tutorial",
    "range": {
    "path": "awards.wins",
    "gte": 10
    },
    "sort": {
    "awards.wins": -1,
    }
    }
    $limit
    5
    $project
    {
    title: 1,
    released: 1,
    year: 1
    }

    If you enabled Auto Preview, MongoDB Compass displays the following documents next to the $limit pipeline stage:

    [
    {
    title: '12 Years a Slave',
    awards: { wins: 267 }
    },
    {
    title: 'Gravity',
    awards: { wins: 231 }
    },
    {
    title: 'Gravity',
    awards: { wins: 231 }
    },
    {
    title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
    awards: { wins: 210 }
    },
    {
    title: 'Boyhood',
    awards: { wins: 185 }
    }
    ]
1
  1. Create a new directory called sort-by-numbers-example and initialize your project with the dotnet new command.

    mkdir sort-by-numbers-example
    cd sort-by-numbers-example
    dotnet new console
  2. Add the .NET/C# Driver to your project as a dependency.

    dotnet add package MongoDB.Driver
2
  1. Replace the contents of the Program.cs file with the following code.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

      The query uses the following pipeline stages:

      • $search stage to search the awards.wins field and sort the results in descending order.

      • $limit stage to limit the output to 5 results.

      • $project stage to exclude all fields except title and awards.wins.

    • Iterates over the cursor to print the documents that match the query.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class SortByNumbers
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define search options
    23 var searchOptions = new SearchOptions<MovieDocument>()
    24 {
    25 Sort = Builders<MovieDocument>.Sort.Descending(movies => movies.Awards.Wins),
    26 IndexName = "sort-tutorial"
    27 };
    28
    29 // define and run pipeline
    30 var results = moviesCollection.Aggregate()
    31 .Search(
    32 Builders<MovieDocument>.Search.Range(movie => movie.Awards.Wins, SearchRangeBuilder.Gte(10)), searchOptions)
    33 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    34 .Exclude(movie => movie.Id)
    35 .Include(movie => movie.Title)
    36 .Include(movie => movie.Awards.Wins))
    37 .Limit(5)
    38 .ToList();
    39
    40 // print results
    41 foreach (var movie in results)
    42 {
    43 Console.WriteLine(movie.ToJson());
    44 }
    45 }
    46}
    47
    48[BsonIgnoreExtraElements]
    49public class MovieDocument
    50{
    51 [BsonIgnoreIfDefault]
    52 public ObjectId Id { get; set; }
    53 public string Title { get; set; }
    54 public Award Awards { get; set; }
    55}
    56
    57public class Award
    58{
    59 [BsonIgnoreIfDefault]
    60 public int Wins { get; set; }
    61}
  2. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
dotnet run Program.cs
{ "title" : "12 Years a Slave", "awards" : { "wins" : 267 } }
{ "title" : "Gravity", "awards" : { "wins" : 231 } }
{ "title" : "Gravity", "awards" : { "wins" : 231 } }
{ "title" : "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards" : { "wins" : 210 } }
{ "title" : "Boyhood", "awards" : { "wins" : 185 } }
1
2

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

    The query uses the following pipeline stages:

    • $search stage to search the awards.wins field and sort the results in descending order.

    • $limit stage to limit the output to 5 results.

    • $project stage to exclude all fields except title and awards.wins.

  • Iterates over the cursor to print the documents that match the query.

1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("sample_mflix").Collection("movies")
22
23 // define pipeline stages
24 searchStage := bson.D{{"$search", bson.D{
25 {"index", "sort-tutorial"},
26 {"range", bson.D{
27 {"path", "awards.wins"},
28 {"gte", 10},
29 }},
30 {"sort", bson.D{{"awards.wins", -1}}},
31 }}}
32 limitStage := bson.D{{"$limit", 5}}
33 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"awards.wins", 1}, {"_id", 0}}}}
34
35 // run pipeline
36 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
37 if err != nil {
38 panic(err)
39 }
40
41 // print results
42 var results []bson.D
43 if err = cursor.All(context.TODO(), &results); err != nil {
44 panic(err)
45 }
46 for _, result := range results {
47 fmt.Println(result)
48 }
49}

Note

Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
go run sort-by-numbers.go
[{title 12 Years a Slave} {awards [{wins 267}]}]
[{title Gravity} {awards [{wins 231}]}]
[{title Gravity} {awards [{wins 231}]}]
[{title Birdman: Or (The Unexpected Virtue of Ignorance)} {awards [{wins 210}]}]
[{title Boyhood} {awards [{wins 185}]}]
1
junit
4.11 or higher version
mongodb-driver-sync
4.3.0 or higher version
slf4j-log4j12
1.7.30 or higher version
2
  1. Create a file named SortByNumbers.java.

  2. Copy and paste the following code into the SortByNumbers.java file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

      The query uses the following pipeline stages:

      • $search stage to search the awards.wins field and sort the results in descending order.

      • $limit stage to limit the output to 5 results.

      • $project stage to exclude all fields except title and awards.wins.

    • Iterates over the cursor to print the documents that match the query.

    1import java.util.Arrays;
    2
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import com.mongodb.client.MongoClient;
    9import com.mongodb.client.MongoClients;
    10import com.mongodb.client.MongoCollection;
    11import com.mongodb.client.MongoDatabase;
    12import org.bson.Document;
    13
    14public class SortByNumbers {
    15 public static void main( String[] args ) {
    16 // define query
    17 Document agg =
    18 new Document("$search",
    19 new Document("index", "sort-tutorial")
    20 .append("range",
    21 new Document("path", "awards.wins")
    22 .append("gte", 10L))
    23 .append("sort",
    24 new Document("awards.wins", -1L)));
    25
    26 // specify connection
    27 String uri = "<connection-string>";
    28
    29 // establish connection and set namespace
    30 try (MongoClient mongoClient = MongoClients.create(uri)) {
    31 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    32 MongoCollection<Document> collection = database.getCollection("movies");
    33
    34 // run query and print results
    35 collection.aggregate(Arrays.asList(agg,
    36 limit(5),
    37 project(fields(excludeId(), include("title"), include("awards.wins")))))
    38 .forEach(doc -> System.out.println(doc.toJson()));
    39 }
    40 }
    41}

    Note

    To run the sample code in your Maven environment, add the following code above the import statements in your file.

    package com.mongodb.drivers;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run the SortByNumbers.java file.

    javac SortByNumbers.java
    java SortByNumbers
    {"title": "12 Years a Slave", "awards": {"wins": 267}}
    {"title": "Gravity", "awards": {"wins": 231}}
    {"title": "Gravity", "awards": {"wins": 231}}
    {"title": "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards": {"wins": 210}}
    {"title": "Boyhood", "awards": {"wins": 185}}
1
mongodb-driver-kotlin-coroutine
4.10.0 or higher version
2
  1. Create a file named SortByNumbers.kt.

  2. Copy and paste the following code into the SortByNumbers.kt file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

      The query uses the following pipeline stages:

      • $search stage to search the awards.wins field and sort the results in descending order.

      • $limit stage to limit the output to 5 results.

      • $project stage to exclude all fields except title and awards.wins.

    • Prints the documents that match the query from the AggregateFlow instance.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12 val database = mongoClient.getDatabase("sample_mflix")
    13 val collection = database.getCollection<Document>("movies")
    14
    15 runBlocking {
    16 // define query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "sort-tutorial")
    20 .append(
    21 "range",
    22 Document("path", "awards.wins")
    23 .append("gte", 10L)
    24 )
    25 .append(
    26 "sort",
    27 Document("awards.wins", -1L)
    28 )
    29 )
    30
    31 // run query and print results
    32 val resultsFlow = collection.aggregate<Document>(
    33 listOf(
    34 agg,
    35 limit(5),
    36 project(fields(
    37 excludeId(),
    38 include("title", "awards.wins")
    39 ))
    40 )
    41 )
    42 resultsFlow.collect { println(it) }
    43 }
    44 mongoClient.close()
    45}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the SortByNumbers.kt file.

    When you run the SortByNumbers.kt program in your IDE, it prints the following documents:

    Document{{title=12 Years a Slave, awards=Document{{wins=267}}}}
    Document{{title=Gravity, awards=Document{{wins=231}}}}
    Document{{title=Gravity, awards=Document{{wins=231}}}}
    Document{{title=Birdman: Or (The Unexpected Virtue of Ignorance), awards=Document{{wins=210}}}}
    Document{{title=Boyhood, awards=Document{{wins=185}}}}
1
2

The code example performs the following tasks:

  • Imports mongodb, MongoDB's Node.js driver.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

    The query uses the following pipeline stages:

    • $search stage to search the awards.wins field and sort the results in descending order.

    • $limit stage to limit the output to 5 results.

    • $project stage to exclude all fields except title and awards.wins.

  • Iterates over the cursor to print the documents that match the query.

1const { MongoClient } = require("mongodb");
2
3// Replace the uri string with your MongoDB deployments connection string.
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12
13 // set namespace
14 const database = client.db("sample_mflix");
15 const coll = database.collection("movies");
16
17 // define pipeline
18 const agg = [
19 {
20 '$search': {
21 'index': 'sort-tutorial',
22 'range': {
23 'path': 'awards.wins',
24 'gte': 10
25 },
26 'sort': {
27 'awards.wins': -1
28 }
29 }
30 }, {
31 '$limit': 5
32 }, {
33 '$project': {
34 '_id': 0,
35 'title': 1,
36 'awards.wins': 1
37 }
38 }
39 ];
40
41 // run pipeline
42 const result = await coll.aggregate(agg);
43
44 // print results
45 await result.forEach((doc) => console.log(doc));
46
47 } finally {
48 await client.close();
49 }
50}
51run().catch(console.dir);

Note

Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
node sort-by-numbers.js
{ title: '12 Years a Slave', awards: { wins: 267 } }
{ title: 'Gravity', awards: { wins: 231 } }
{ title: 'Gravity', awards: { wins: 231 } }
{
title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
awards: { wins: 210 }
}
{ title: 'Boyhood', awards: { wins: 185 } }
1
2

The following code example:

  • Imports pymongo, MongoDB's Python driver, and the dns module, which is required to connect pymongo to Atlas using a DNS seed list connection string.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • The following query shows how to sort the results by a numeric field. It uses the range operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

    The query uses the following pipeline stages:

    • $search stage to search the awards.wins field and sort the results in descending order.

    • $limit stage to limit the output to 5 results.

    • $project stage to exclude all fields except title and awards.wins.

  • Iterates over the cursor to print the documents that match the query.

1import datetime
2import pymongo
3
4# connect to your Atlas cluster
5client = pymongo.MongoClient('<connection-string>')
6
7# define pipeline
8pipeline = [
9 {
10 '$search': {
11 'index': 'sort-tutorial',
12 'range': {
13 'path': 'awards.wins',
14 'gte': 10
15 },
16 'sort': {
17 'awards.wins': -1
18 }
19 }
20 }, {
21 '$limit': 5
22 }, {
23 '$project': {'_id': 0, 'title': 1, 'awards.wins': 1
24 }
25 }
26]
27
28# run pipeline
29result = client['sample_mflix']['movies'].aggregate(pipeline)
30
31# print results
32for i in result:
33 print(i)

Note

Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
python sort-by-numbers.py
{'title': '12 Years a Slave', 'awards': {'wins': 267}}
{'title': 'Gravity', 'awards': {'wins': 231}}
{'title': 'Gravity', 'awards': {'wins': 231}}
{'title': 'Birdman: Or (The Unexpected Virtue of Ignorance)', 'awards': {'wins': 210}}
{'title': 'Boyhood', 'awards': {'wins': 185}}

The $search stage in the sample queries use the sort option to sort the Atlas Search results by the indexed date field.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

Click the Query button to the right of the index to query.

4

Click Edit Query to view a default query syntax sample in JSON format.

5

The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

  • wildcard operator to search for movie titles that begin with Summer.

  • near operator to search for movies that were released in and about five months before or after April 18, 2014.

    Note

    When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

[
{
$search: {
"index": "sort-tutorial",
"compound": {
"filter": [{
"wildcard": {
"query": "Summer*",
"path": "title"
}
}],
"must": [{
"near": {
"pivot": 13149000000,
"path": "released",
"origin": ISODate("2014-04-18T00:00:00.000+00:00")
}
}]
},
"sort": {
"released": -1,
"title": 1
}
}
}
]
SCORE: 0.348105788230896 _id: "573a13f0f29313caabddaf7a"
countries: Array
runtime: 104
cast: Array
...
title: "Summer Nights"
...
released: 2015-01-28T00:00:00.000+00:00
...
SCORE: 0.5917375683784485 _id: "573a13e6f29313caabdc673b"
plot: "25-year-old Iiris and Karoliina have been best friends since childhood…"
genres: Array
runtime: 90
...
title: "Summertime"
...
released: 2014-08-01T00:00:00.000+00:00
...
SCORE: 0.9934720396995544 _id: "573a13eff29313caabdd760c"
plot: "Erik Sparrow is one of the lucky ones. He's got a good job. He's in a …"
genres: Array
runtime: 86
...
title: "Summer of Blood"
...
released: 2014-04-17T00:00:00.000+00:00
...
SCORE: 0.15982933342456818 _id: "573a13cff29313caabd8ab74"
plot: "The story of an adult and a teenage couple during a brief summer holid…"
genres: Array
countries: Array
...
title: "Summer Games"
...
released: 2012-02-08T00:00:00.000+00:00
...
SCORE: 0.13038821518421173 _id: "573a13cef29313caabd87f4e"
plot: "Summer of Goliath is a documentary/fiction hybrid that narrates variou…"
genres: Array
runtime: 78
...
title: "Summer of Goliath"
...
released: 2011-07-08T00:00:00.000+00:00
...
SCORE: 0.08124520629644394 _id: "573a13c7f29313caabd7608d"
plot: "A student tries to fix a problem he accidentally caused in OZ, a digit…"
genres: Array
runtime: 114
...
title: "Summer Wars"
...
released: 2009-08-01T00:00:00.000+00:00
SCORE: 0.0711759403347969 _id: "573a13bbf29313caabd54ee6"
plot: "The life of a public school epitomized by disobedient student Jonah Ta…"
genres: Array
runtime: 30
...
title: "Summer Heights High"
...
released: 2008-11-09T00:00:00.000+00:00
...
SCORE: 0.06951779872179031 _id: "573a13bff29313caabd5f935"
plot: "On his spring break at the seaside, with his wife and his four year ol…"
genres: Array
runtime: 102
...
title: "Summer Holiday"
...
released: 2008-09-19T00:00:00.000+00:00
...
SCORE: 0.05834990739822388 _id: "573a13c0f29313caabd628ac"
plot: "Kochi Uehara is a fourth grade student living in the suburb of Tokyo. …"
genres: Array
runtime: 138
...
title: "Summer Days with Coo"
...
released: 2007-07-28T00:00:00.000+00:00
...
SCORE: 0.056174591183662415 _id: "573a13b8f29313caabd4c1d0"
fullplot: "Country girl Yu Hong leaves her village, her family and her lover to s…"
genres: Array
runtime: 158
...
title: "Summer Palace"
...
released: 2007-04-18T00:00:00.000+00:00
...
6

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

1

Open mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see Connect via mongosh.

2

Run the following command at mongosh prompt:

use sample_mflix
3

The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

  • wildcard operator to search for movie titles that begin with Summer.

  • near operator to search for movies that were released in and about five months before or after April 18, 2014.

    Note

    When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

The query uses the following pipeline stages:

  • $search stage to search the title and released fields and then sort the results by the released field in descending order.

  • $limit stage to limit the output to 5 results.

  • $project stage to:

    • Exclude all fields except title and released.

    • Add a field named score.

1db.movies.aggregate([
2{
3 $search: {
4 "index": "sort-tutorial",
5 "compound": {
6 "filter": [{
7 "wildcard": {
8 "query": "Summer*",
9 "path": "title"
10 }
11 }],
12 "must": [{
13 "near": {
14 "pivot": 13149000000,
15 "path": "released",
16 "origin": ISODate("2014-04-18T00:00:00.000+00:00")
17 }
18 }]
19 },
20 "sort": {
21 "released": -1
22 }
23 }
24},
25{
26 $limit: 5
27},
28{
29 $project: {
30 "_id": 0,
31 "title": 1,
32 "released": 1,
33 "score": {
34 "$meta": "searchScore"
35 }
36 }
37}])
[
{
title: 'Summer Nights',
released: ISODate("2015-01-28T00:00:00.000Z"),
score: 0.348105788230896
},
{
title: 'Summertime',
released: ISODate("2014-08-01T00:00:00.000Z"),
score: 0.5917375683784485
},
{
title: 'Summer of Blood',
released: ISODate("2014-04-17T00:00:00.000Z"),
score: 0.9934720396995544
},
{
title: 'Summer Games',
released: ISODate("2012-02-08T00:00:00.000Z"),
score: 0.15982933342456818
},
{
title: 'Summer of Goliath',
released: ISODate("2011-07-08T00:00:00.000Z"),
score: 0.13038821518421173
}
]
1

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.

2

On the Database screen, click the sample_mflix database, then click the movies collection.

3

The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

  • wildcard operator to search for movie titles that begin with Summer.

  • near operator to search for movies that were released in and about five months before or after April 18, 2014.

    Note

    When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

The query uses the following pipeline stages:

  • $search stage to search the title and released fields and then sort the results by the released field in descending order.

  • $limit stage to limit the output to 5 results.

  • $project stage to:

    • Exclude all fields except title and released.

    • Add a field named score.

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.

    Pipeline Stage
    Query
    $search
    {
    "index": "sort-tutorial",
    "compound": {
    "filter": [{
    "wildcard": {
    "query": "Summer*",
    "path": "title"
    }
    }],
    "must": [{
    "near": {
    "pivot": 13149000000,
    "path": "released",
    "origin": ISODate("2014-04-18T00:00:00.000+00:00")
    }
    }]
    },
    "sort": {
    "released": -1
    }
    }
    $limit
    5
    $project
    {
    _id: 0,
    title: 1,
    released: 1,
    score: { $meta: "searchScore" }
    }

    If you enabled Auto Preview, MongoDB Compass displays the following documents next to the $limit pipeline stage:

    {
    title: 'Summer Nights',
    released: 2015-01-28T00:00:00.000+00:00,
    score: 0.348105788230896
    },
    {
    title: 'Summertime',
    released: 2014-08-01T00:00:00.000+00:00,
    score: 0.5917375683784485
    },
    {
    title: 'Summer of Blood',
    released: 2014-04-17T00:00:00.000+00:00,
    score: 0.9934720396995544
    },
    {
    title: 'Summer Games',
    released: 2012-02-08T00:00:00.000+00:00,
    score: 0.15982933342456818
    },
    {
    title: 'Summer of Goliath',
    released: 2011-07-08T00:00:00.000+00:00,
    score: 0.13038821518421173
    }
1
  1. Create a new directory called sort-by-date-example and initialize your project with the dotnet new command.

    mkdir sort-by-date-example
    cd sort-by-date-example
    dotnet new console
  2. Add the .NET/C# Driver to your project as a dependency.

    dotnet add package MongoDB.Driver
2
  1. Replace the contents of the Program.cs file with the following code.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

      • wildcard operator to search for movie titles that begin with Summer.

      • near operator to search for movies that were released in and about five months before or after April 18, 2014.

        Note

        When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

      The query uses the following pipeline stages:

      • $search stage to search the title and released fields and then sort the results by the released field in descending order.

      • $limit stage to limit the output to 5 results.

      • $project stage to:

        • Exclude all fields except title and released.

        • Add a field named score.

    • Iterates over the cursor to print the documents that match the query.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class SortByStrings
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22
    23 // declare data for compound query
    24 var originDate = new DateTime(2014, 04, 18, 0, 0, 0, DateTimeKind.Utc);
    25
    26 // define search options
    27 var searchOptions = new SearchOptions<MovieDocument>()
    28 {
    29 Sort = Builders<MovieDocument>.Sort.Descending(movie => movie.Released),
    30 IndexName = "sort-tutorial"
    31 };
    32
    33 // define and run pipeline
    34 var results = moviesCollection.Aggregate()
    35 .Search(Builders<MovieDocument>.Search.Compound()
    36 .Filter(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Summer*"))
    37 .Must(Builders<MovieDocument>.Search.Near(movie => movie.Released, originDate, 13149000000)), searchOptions)
    38 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    39 .Include(movie => movie.Released)
    40 .Include(movie => movie.Title)
    41 .Exclude(movie => movie.Id)
    42 .MetaSearchScore(movie => movie.Score))
    43 .Limit(5)
    44 .ToList();
    45
    46 // print results
    47 foreach (var movie in results)
    48 {
    49 Console.WriteLine(movie.ToJson());
    50 }
    51 }
    52}
    53
    54[BsonIgnoreExtraElements]
    55public class MovieDocument
    56{
    57 [BsonIgnoreIfDefault]
    58 public ObjectId Id { get; set; }
    59 public DateTime Released { get; set; }
    60 public string Title { get; set; }
    61 public double Score { get; set; }
    62}
  2. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
dotnet run Program.cs
{ "released" : ISODate("2015-01-28T00:00:00Z"), "title" : "Summer Nights", "score" : 0.348105788230896 }
{ "released" : ISODate("2014-08-01T00:00:00Z"), "title" : "Summertime", "score" : 0.59173756837844849 }
{ "released" : ISODate("2014-04-17T00:00:00Z"), "title" : "Summer of Blood", "score" : 0.99347203969955444 }
{ "released" : ISODate("2014-01-17T00:00:00Z"), "title" : "Summer in February", "score" : 0.62580311298370361 }
{ "released" : ISODate("2012-02-08T00:00:00Z"), "title" : "Summer Games", "score" : 0.15982933342456818 }
1
2

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

    • wildcard operator to search for movie titles that begin with Summer.

    • near operator to search for movies that were released in and about five months before or after April 18, 2014.

      Note

      When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

    The query uses the following pipeline stages:

    • $search stage to search the title and released fields and then sort the results by the released field in descending order.

    • $limit stage to limit the output to 5 results.

    • $project stage to:

      • Exclude all fields except title and released.

      • Add a field named score.

  • Iterates over the cursor to print the documents that match the query.

1package main
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "go.mongodb.org/mongo-driver/bson"
9 "go.mongodb.org/mongo-driver/mongo"
10 "go.mongodb.org/mongo-driver/mongo/options"
11)
12
13func main() {
14 // connect to your Atlas cluster
15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string"))
16 if err != nil {
17 panic(err)
18 }
19 defer client.Disconnect(context.TODO())
20
21 // set namespace
22 collection := client.Database("sample_mflix").Collection("movies")
23
24 // define pipeline stages
25 searchStage := bson.D{{"$search", bson.M{
26 "index": "sort-tutorial",
27 "compound": bson.M{
28 "filter": bson.A{
29 bson.M{
30 "wildcard": bson.D{
31 {"path", "title"},
32 {"query", "Summer*"},
33 }},
34 },
35 "must": bson.A{
36 bson.M{
37 "near": bson.M{
38 "path": "released",
39 "origin": time.Date(2014, time.April, 18, 0, 0, 0, 0, time.UTC),
40 "pivot": 13149000000}},
41 },
42 },
43 "sort": bson.D{{"released", -1}},
44 }}}
45
46 limitStage := bson.D{{"$limit", 5}}
47 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
48
49 // run pipeline
50 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
51 if err != nil {
52 panic(err)
53 }
54
55 // print results
56 var results []bson.D
57 if err = cursor.All(context.TODO(), &results); err != nil {
58 panic(err)
59 }
60 for _, result := range results {
61 fmt.Println(result)
62 }
63}

Note

Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
go run sort-by-date.go
[{title Summer Nights} {released 1422403200000} {score 0.348105788230896}]
[{title Summertime} {released 1406851200000} {score 0.5917375683784485}]
[{title Summer of Blood} {released 1397692800000} {score 0.9934720396995544}]
[{title Summer Games} {released 1328659200000} {score 0.15982933342456818}]
[{title Summer of Goliath} {released 1310083200000} {score 0.13038821518421173}]
1
junit
4.11 or higher version
mongodb-driver-sync
4.3.0 or higher version
slf4j-log4j12
1.7.30 or higher version
2
  1. Create a file named SortByDate.java.

  2. Copy and paste the following code into the SortByDate.java file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

      • wildcard operator to search for movie titles that begin with Summer.

      • near operator to search for movies that were released in and about five months before or after April 18, 2014.

        Note

        When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

      The query uses the following pipeline stages:

      • $search stage to search the title and released fields and then sort the results by the released field in descending order.

      • $limit stage to limit the output to 5 results.

      • $project stage to:

        • Exclude all fields except title and released.

        • Add a field named score.

    • Iterates over the cursor to print the documents that match the query.

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13import java.time.Instant;
    14import java.util.Date;
    15
    16public class SortByDate {
    17 public static void main( String[] args ) {
    18 // define query
    19 Document agg =
    20 new Document("$search",
    21 new Document("index", "sort-tutorial")
    22 .append("compound",
    23 new Document("filter", Arrays.asList(new Document("wildcard",
    24 new Document("query", "Summer*")
    25 .append("path", "title"))))
    26 .append("must", Arrays.asList(new Document("near",
    27 new Document("pivot", 13149000000L)
    28 .append("path", "released")
    29 .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00")))))))
    30 .append("sort", new Document("released", -1)));
    31
    32 // specify connection
    33 String uri = "<connection-string>";
    34
    35 // establish connection and set namespace
    36 try (MongoClient mongoClient = MongoClients.create(uri)) {
    37 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    38 MongoCollection<Document> collection = database.getCollection("movies");
    39 // run query and print results
    40 collection.aggregate(Arrays.asList(agg,
    41 limit(5),
    42 project(fields(exclude("_id"), include("title"), include("released"), computed("score", new Document("$meta", "searchScore"))))))
    43 .forEach(doc -> System.out.println(doc.toJson()));
    44 }
    45 }
    46}

    Note

    To run the sample code in your Maven environment, add the following code above the import statements in your file.

    package com.mongodb.drivers;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run the SortDateForSpeed.java file.

    javac SortByDate.java
    java SortByDate
    {"title": "Summer Nights", "released": {"$date": "2015-01-28T00:00:00Z"}, "score": 0.348105788230896}
    {"title": "Summertime", "released": {"$date": "2014-08-01T00:00:00Z"}, "score": 0.5917375683784485}
    {"title": "Summer of Blood", "released": {"$date": "2014-04-17T00:00:00Z"}, "score": 0.9934720396995544}
    {"title": "Summer Games", "released": {"$date": "2012-02-08T00:00:00Z"}, "score": 0.15982933342456818}
    {"title": "Summer of Goliath", "released": {"$date": "2011-07-08T00:00:00Z"}, "score": 0.13038821518421173}
1
mongodb-driver-kotlin-coroutine
4.10.0 or higher version
2
  1. Create a file named SortByDate.kt.

  2. Copy and paste the following code into the SortByDate.kt file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

      • wildcard operator to search for movie titles that begin with Summer.

      • near operator to search for movies that were released in and about five months before or after April 18, 2014.

        Note

        When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

      The query uses the following pipeline stages:

      • $search stage to search the title and released fields and then sort the results by the released field in descending order.

      • $limit stage to limit the output to 5 results.

      • $project stage to:

        • Exclude all fields except title and released.

        • Add a field named score.

    • Prints the documents that match the query from the AggregateFlow instance.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7import java.time.Instant
    8import java.util.*
    9
    10fun main() {
    11 // establish connection and set namespace
    12 val uri = "<connection-string>"
    13 val mongoClient = MongoClient.create(uri)
    14 val database = mongoClient.getDatabase("sample_mflix")
    15 val collection = database.getCollection<Document>("movies")
    16
    17 runBlocking {
    18 // define query
    19 val agg = Document(
    20 "\$search",
    21 Document("index", "sort-tutorial")
    22 .append(
    23 "compound",
    24 Document(
    25 "filter", listOf(
    26 Document(
    27 "wildcard",
    28 Document("query", "Summer*")
    29 .append("path", "title")
    30 )
    31 )
    32 )
    33 .append(
    34 "must", listOf(
    35 Document(
    36 "near",
    37 Document("pivot", 13149000000L)
    38 .append("path", "released")
    39 .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00")))
    40 )
    41 )
    42 )
    43 )
    44 .append("sort", Document("released", -1))
    45 )
    46
    47 // run query and print results
    48 val resultsFlow = collection.aggregate<Document>(
    49 listOf(
    50 agg,
    51 limit(5),
    52 project(fields(
    53 excludeId(),
    54 include("title", "released"),
    55 computed("score", Document("\$meta", "searchScore"))
    56 ))
    57 )
    58 )
    59 resultsFlow.collect { println(it) }
    60 }
    61 mongoClient.close()
    62}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the SortByDate.kt file.

    When you run the SortByDate.kt program in your IDE, it prints the following documents:

    Document{{title=Summer Nights, released=Tue Jan 27 19:00:00 EST 2015, score=0.348105788230896}}
    Document{{title=Summertime, released=Thu Jul 31 20:00:00 EDT 2014, score=0.5917375683784485}}
    Document{{title=Summer of Blood, released=Wed Apr 16 20:00:00 EDT 2014, score=0.9934720396995544}}
    Document{{title=Summer Games, released=Tue Feb 07 19:00:00 EST 2012, score=0.15982933342456818}}
    Document{{title=Summer of Goliath, released=Thu Jul 07 20:00:00 EDT 2011, score=0.13038821518421173}}
1
2

The code example performs the following tasks:

  • Imports mongodb, MongoDB's Node.js driver.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

    • wildcard operator to search for movie titles that begin with Summer.

    • near operator to search for movies that were released in and about five months before or after April 18, 2014.

      Note

      When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

    The query uses the following pipeline stages:

    • $search stage to search the title and released fields and then sort the results by the released field in descending order.

    • $limit stage to limit the output to 5 results.

    • $project stage to:

      • Exclude all fields except title and released.

      • Add a field named score.

  • Iterates over the cursor to print the documents that match the query.

1const { MongoClient } = require("mongodb");
2
3// Replace the uri string with your MongoDB deployments connection string.
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12
13 // set namespace
14 const database = client.db("sample_mflix");
15 const coll = database.collection("movies");
16
17 // define pipeline
18 const agg = [
19 {$search: {
20 index: "sort-tutorial",
21 compound: {
22 filter: {wildcard: {query: "Summer*", path: "title"}},
23 must: [{near: {path: "released", origin: new Date("2014-04-18T00:00:00.000Z"), pivot: 13149000000}}]
24 },
25 sort: { released: -1 }
26 }},
27 {$limit: 5},
28 {$project: {_id: 0, title: 1, released: 1, score: {$meta: "searchScore"}}}
29 ];
30
31 // run pipeline
32 const result = await coll.aggregate(agg);
33
34 // print results
35 await result.forEach((doc) => console.log(doc));
36
37 } finally {
38 await client.close();
39 }
40}
41run().catch(console.dir);

Note

Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
node sort-by-date.js
{
title: 'Summer Nights',
released: 2015-01-28T00:00:00.000Z,
score: 0.348105788230896
}
{
title: 'Summertime',
released: 2014-08-01T00:00:00.000Z,
score: 0.5917375683784485
}
{
title: 'Summer of Blood',
released: 2014-04-17T00:00:00.000Z,
score: 0.9934720396995544
}
{
title: 'Summer Games',
released: 2012-02-08T00:00:00.000Z,
score: 0.15982933342456818
}
{
title: 'Summer of Goliath',
released: 2011-07-08T00:00:00.000Z,
score: 0.13038821518421173
}
1
2

The following code example:

  • Imports pymongo, MongoDB's Python driver, and the dns module, which is required to connect pymongo to Atlas using a DNS seed list connection string.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • The following query shows how to run a compound query and sort the results by a date field. It uses the following operators:

    • wildcard operator to search for movie titles that begin with Summer.

    • near operator to search for movies that were released in and about five months before or after April 18, 2014.

      Note

      When you use pivot on a date field, its unit of measure is in milliseconds. Atlas Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see near.

    The query uses the following pipeline stages:

    • $search stage to search the title and released fields and then sort the results by the released field in descending order.

    • $limit stage to limit the output to 5 results.

    • $project stage to:

      • Exclude all fields except title and released.

      • Add a field named score.

  • Iterates over the cursor to print the documents that match the query.

1import datetime
2import pymongo
3
4# connect to your Atlas cluster
5client = pymongo.MongoClient('<connection-string>')
6
7# define pipeline
8pipeline = [
9 {'$search': {
10 'index': 'sort-tutorial',
11 'compound': {
12 'filter': {'wildcard': {'query': 'Summer*', 'path': 'title'}},
13 'must': {'near': {
14 "path": "released",
15 "origin": datetime.datetime(2014, 4, 18, 0, 0, 0, 0),
16 "pivot": 13149000000
17 }}},
18 'sort': { 'released': -1 }}},
19 {'$limit': 5},
20 {'$project': {'_id': 0, 'title': 1, 'released': 1, 'score': {'$meta': 'searchScore'}}}
21]
22
23# run pipeline
24result = client['sample_mflix']['movies'].aggregate(pipeline)
25
26# print results
27for i in result:
28 print(i)

Note

Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

3
python sort-date-for-speed.py
{'title': 'Summer Nights', 'released': datetime.datetime(2015, 1, 28, 0, 0), 'score': 0.348105788230896}
{'title': 'Summertime', 'released': datetime.datetime(2014, 8, 1, 0, 0), 'score': 0.5917375683784485}
{'title': 'Summer of Blood', 'released': datetime.datetime(2014, 4, 17, 0, 0), 'score': 0.9934720396995544}
{'title': 'Summer Games', 'released': datetime.datetime(2012, 2, 8, 0, 0), 'score': 0.15982933342456818}
{'title': 'Summer of Goliath', 'released': datetime.datetime(2011, 7, 8, 0, 0), 'score': 0.13038821518421173}

The $search stage in the sample queries use the sort option to sort the Atlas Search results by the indexed string field.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

Click the Query button to the right of the index to query.

4

Click Edit Query to view a default query syntax sample in JSON format.

5

The following query shows how to query and sort the results by a string field. It searches for titles that begin with Prance or Prince and sorts the results by the title field in ascending order.

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

[
{
$search: {
"index": "sort-tutorial",
"compound": {
"should": [{
"wildcard": {
"query": ["Prance*"],
"path": "title",
"allowAnalyzedField": true
}
},
{
"wildcard": {
"query": ["Prince*"],
"path": "title",
"allowAnalyzedField": true
}
}]
},
"sort": {
"title": 1
}
}
}
]
SCORE: 1 _id: "573a1398f29313caabceb98e"
plot: "A farm girl nurses a wounded reindeer she believes is one of Santa's, …"
genres: Array
runtime: 103
...
title: "Prancer"
...
SCORE: 1 _id: "573a13a5f29313caabd14f54"
plot: "Preteen brothers from a broken marriage live with their mother, Denise…"
genres: Array
runtime: 91
...
title: "Prancer Returns"
...
SCORE: 1 _id: "573a13f5f29313caabde3755"
plot: "A troubled teenager attempts to conquer the love of his life by becomi…"
genres: Array
runtime: 78
...
title: "Prince"
...
SCORE: 1 _id: "573a13d8f29313caabda665f"
fullplot: "Two highway road workers spend the summer of 1988 away from their city…"
imdb: Object
year: 2013
...
title: "Prince Avalanche"
...
SCORE: 1 _id: "573a13bdf29313caabd5898a"
plot: "A New York street drama about the lives of immigrants in America seeki…"
genres: Array
runtime: 70
...
title: "Prince of Broadway"
...
SCORE: 1 _id: "573a1398f29313caabcea967"
fullplot: "A sinister secret has been kept in the basement of an abandoned Los An…"
imdb: Object
year: 1987
...
title: "Prince of Darkness"
...
SCORE: 1 _id: "573a1393f29313caabcde40d"
plot: "An unscrupulous agent for the Borgias suffers a change of heart when a…"
genres: Array
runtime: 107
...
title: "Princess of Foxes"
...
SCORE: 1 _id: "573a13b5f29313caabd43816"
plot: "A young fugitive prince and princess must stop a villain who unknowing…"
genres: Array
runtime: 116
...
title: "Prince of Persia: The Sands of Time"
...
SCORE: 1 _id: "573a1397f29313caabce8081"
plot: "A New York City narcotics detective reluctantly agrees to cooperate wi…"
genres: Array
runtime: 167
...
title: "Prince of the City"
...
SCORE: 1 _id: "573a13a2f29313caabd0a767"
plot: "Six old-style funny silhouetted fairy tales for not so-old-style peopl…"
genres: Array
runtime: 70
...
title: "Princes and Princesses"
...

The Atlas Search results contain documents with movie titles that begin with Prance and Prince. Atlas Search returns titles with Prance followed by Prince because Atlas Search sorts documents by the title field in ascending order.

6

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

1

Open mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see Connect via mongosh.

2

Run the following command at mongosh prompt:

use sample_mflix
3

The following query shows how to query and sort the results by a string field. It searches for titles that begin with Prance or Prince and sorts the results by the title field in ascending order.

The query uses the following pipeline stages:

  • $search to search the title field using the should clause with the wildcard operator to search for titles that begin with Prance and Prince. The query also specifies that results must be sorted by the title field in ascending order.

  • $limit stage to limit the output to 5 results.

  • $project stage to:

    • Exclude all fields except title.

    • Add a field named score.

1db.movies.aggregate([{
2 $search: {
3 "index": "sort-tutorial",
4 "compound": {
5 "should": [{
6 "wildcard": {
7 "query": ["Prance*"],
8 "path": "title",
9 "allowAnalyzedField": true
10 }
11 },
12 {
13 "wildcard": {
14 "query": ["Prince*"],
15 "path": "title",
16 "allowAnalyzedField": true
17 }
18 }]
19 },
20 "sort": {
21 "title": 1
22 }
23 }},
24 {
25 $limit: 5
26 },
27 {
28 $project: {
29 "_id": 0,
30 "title": 1,
31 "score": { "$meta": "searchScore" }
32 }
33 }
34])