Docs Menu
Docs Home
/
MongoDB Atlas
/ /

How to Run Atlas Search Queries with a Date Range Filter

On this page

  • Create the Atlas Search Index With Dynamic Mapping
  • Run a Compound Query

This tutorial describes how to create an index with dynamic mapping on the sample_mflix.movies collection. It shows how to run compound queries against the released field using the range and near operators. It takes you through the following steps:

  1. Set up an Atlas Search index with dynamic mapping for the sample_mflix.movies collection.

  2. Run Atlas Search compound queries against the released field in the sample_mflix.movies collection.

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.

In this section, we create an Atlas Search index that uses dynamic mapping to index the fields in the sample_mflix.movies collection.

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

  2. If it is 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.

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.

  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.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

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 date-range-tutorial.

    Note

    If you name your index default, you don't need to specify an index parameter when using the $search pipeline stage. Otherwise, you must specify the index name using the index parameter.

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

6

You can create an Atlas Search index that uses dynamic mappings or static mappings. To learn more about dynamic and static mappings, see Static and Dynamic Mappings.

The following index definition dynamically indexes the fields of supported types in the movies collection. 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. Review the "date-range-tutorial" index definition for the movies collection.

  1. Click Next.

  2. Review the index definition.

    Your index definition should look similar to the following:

    {
    "mappings": {
    "dynamic": true
    }
    }

    The above index definition dynamically indexes the fields of supported types in each document in the movies collection.

  3. Click Next.

7
8
9

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

10

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.


➤ Use the Select your language drop-down menu to set the language of the example on this page.


You can use the compound operator to combine two or more operators and clauses into a single query. This tutorial uses the compound operator clauses to search for movies in the specified date range. In this section, connect to your Atlas cluster and run the sample queries using the compound operator against the released field in the sample_mflix.movies collection.

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

  2. If it is 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.

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.

  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.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

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 example uses the compound operator with subqueries to search for movies between the years 2010 to 2015. The query uses the following clauses:

  • A must clause to search for movies released between 2015-01-01 and 2015-12-31

  • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

The query includes a $limit stage to limit the output to 6 results and a $project stage to:

  • Exclude all fields except title, released, and genres fields

  • Add a field named score

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

1[
2 {
3 $search: {
4 "index": "date-range-tutorial",
5 "compound": {
6 "must": [{
7 "range": {
8 "path": "released",
9 "gt": ISODate("2015-01-01T00:00:00.000Z"),
10 "lt": ISODate("2015-12-31T00:00:00.000Z")
11 }
12 }],
13 "should": [{
14 "near": {
15 "path": "released",
16 "origin": ISODate("2015-07-01T00:00:00.000+00:00"),
17 "pivot": 2629800000
18 }
19 }]
20 }
21 }
22 }
23]
SCORE: 2 _id: "573a13c4f29313caabd6c383"
fullplot: "When John Connor (Jason Clarke), leader of the human resistance, sends…"
imdb: Object
year: 2015
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 2 _id: "573a13d9f29313caabdaa9e2"
fullplot: "Three years after Mike bowed out of the stripper life at the top of hi…"
imdb: Object
year: 2015
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 2 _id: "573a13e9f29313caabdcd223"
plot: "A documentary about the power of transformation told through the eyes …"
genres: Array
runtime: 87
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 2 _id: "573a13f4f29313caabde1138"
plot: "Dedicated home care nurse Vlasta lives for her husband Lada, her daugh…"
genres: Array
runtime: 92
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 2 _id: "573a13f9f29313caabdeb320"
plot: "For anyone who has not fully understood the controversial Bitcoin yet,…"
genres: Array
runtime: 60
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 1.9681909084320068 _id: "573a13c2f29313caabd67986"
plot: "A man wakes up alone in the middle of the desert with a black hood on …"
genres: Array
runtime: 90
...
released: 2015-07-02T00:00:00.000+00:00
...
SCORE: 1.9681909084320068 _id: "573a13f4f29313caabde14cf"
plot: "In 1836 the Danish romantic visionary Wulff travels to Africa to creat…"
genres: Array
runtime: 114
...
released: 2015-07-02T00:00:00.000+00:00
...
SCORE: 1.9383430480957031 _id: "573a13d6f29313caabd9f77d"
plot: "The plot of the film has a grandfather telling his grand kids the stor…"
genres: Array
runtime: 78
...
released: 2015-07-03T00:00:00.000+00:00
...
SCORE: 1.9383430480957031 _id: "573a13e3f29313caabdbfb00"
plot: "The story of Amy Winehouse in her own words, featuring unseen archival…"
genres: Array
runtime: 128
...
released: 2015-07-02T00:00:00.000+00:00
...
SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdcbe1e"
plot: "A modern day train hopper fighting to become a successful musician, an…"
genres: Array
runtime: 90
...
released: 2015-07-02T00: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.

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

7

The following example adds on to the previous example.

In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

1[
2 {
3 $search: {
4 "index": "date-range-tutorial",
5 "compound": {
6 "must": [{
7 "range": {
8 "path": "released",
9 "gt": ISODate("2015-01-01T00:00:00.000Z"),
10 "lt": ISODate("2015-12-31T00:00:00.000Z")
11 }
12 }],
13 "should": [{
14 "near": {
15 "path": "released",
16 "origin": ISODate("2015-07-01T00:00:00.000+00:00"),
17 "pivot": 2629800000
18 }
19 }],
20 "mustNot": [{
21 "text": {
22 "query": "documentary",
23 "path": "genres"
24 }
25 }]
26 }
27 }
28 }
29 ]
SCORE: 2 _id: "573a13c4f29313caabd6c383"
fullplot: "When John Connor (Jason Clarke), leader of the human resistance, sends…"
imdb: Object
year: 2015
...
genres:
0: "Action"
1: "Adventure"
2: "Sci-Fi"
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 2 _id: "573a13d9f29313caabdaa9e2"
fullplot: "Three years after Mike bowed out of the stripper life at the top of hi…"
imdb: Object
year: 2015
...
genres:
0: "Comedy"
1: "Drama"
2: "Music"
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 2 _id: "573a13f4f29313caabde1138"
plot: "Dedicated home care nurse Vlasta lives for her husband Lada, her daugh…"
genres:
0: "Comedy"
1: "Drama"
runtime: 92
...
released: 2015-07-01T00:00:00.000+00:00
...
SCORE: 1.9681909084320068 _id: "573a13c2f29313caabd67986"
plot: "A man wakes up alone in the middle of the desert with a black hood on …"
genres:
0: "Drama"
1: "Mystery"
2: "Sci-Fi"
runtime: 90
...
released: 2015-07-02T00:00:00.000+00:00
...
SCORE: 1.9681909084320068 _id: "573a13f4f29313caabde14cf"
plot: "In 1836 the Danish romantic visionary Wulff travels to Africa to creat…"
genres:
0: "Drama"
1: "History"
2: "Romance"
runtime: 114
...
released: 2015-07-02T00:00:00.000+00:00
...
SCORE: 1.9383430480957031 _id: "573a13d6f29313caabd9f77d"
plot: "The plot of the film has a grandfather telling his grand kids the stor…"
genres:
0: "Animation"
1: "Family"
runtime: 78
...
released: 2015-07-03T00:00:00.000+00:00
...
SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdcbe1e"
plot: "A modern day train hopper fighting to become a successful musician, an…"
genres:
0: "Drama"
runtime: 90
...
released: 2015-07-03T00:00:00.000+00:00
...
SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdccb5b"
plot: "A fancy garden party turns into upper class prey when a colony of kill…"
genres:
0: "Comedy"
1: "Horror"
runtime: 87
...
released: 2015-07-03T00:00:00.000+00:00
...
SCORE: 1.9102803468704224 _id: "573a13faf29313caabdec74f"
countries: Array
genres:
0: "Drama"
runtime: 104
...
released: 2015-07-03T00:00:00.000+00:00
...
SCORE: 1.8838474750518799 _id: "573a13eef29313caabdd531d"
plot: "A fantasy love story that drifts between this world and heaven. Chasuk…"
genres:
0: "Comdedy"
countries: Array
...
released: 2015-06-27T00:00:00.000+00:00
...
8

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.

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

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 example uses the compound operator with subqueries to search for movies between the years 2010 to 2015. The query uses the following clauses:

  • A must clause to search for movies released between 2015-01-01 and 2015-12-31

  • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

The query includes a $limit stage to limit the output to 6 results and a $project stage to:

  • Exclude all fields except title, released, and genres fields

  • Add a field named score

db.movies.aggregate([
{
"$search": {
"index": "date-range-tutorial",
"compound": {
"must": [{
"range": {
"path": "released",
"gt": ISODate("2015-01-01T00:00:00.000Z"),
"lt": ISODate("2015-12-31T00:00:00.000Z")
}
}],
"should": [{
"near": {
"path": "released",
"origin": ISODate("2015-07-01T00:00:00.000+00:00"),
"pivot": 2629800000
}
}]
}
}
},
{
"$limit": 6
},
{
"$project": {
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{
"genres": [ "Action", "Adventure", "Sci-Fi" ],
"title": "Terminator Genisys",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama", "Music" ],
"title": "Magic Mike XXL",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Documentary", "Biography", "Drama" ],
"title": "Mala Mala",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama" ],
"title": "Home Care",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Documentary", "News" ],
"title": "Bitcoin: The End of Money as We Know It",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Drama", "Mystery", "Sci-Fi" ],
"title": "Pig",
"released": ISODate("2015-07-02T00:00:00.000Z"),
"score": 1.9681909084320068
}
]

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

4

The following example adds on to the previous example.

In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

db.movies.aggregate([
{
"$search": {
"compound": {
"must": [{
"range": {
"path": "released",
"gt": ISODate("2015-01-01T00:00:00.000Z"),
"lt": ISODate("2015-12-31T00:00:00.000Z")
}
}],
"should": [{
"near": {
"path": "released",
"origin": ISODate("2015-07-01T00:00:00.000+00:00"),
"pivot": 2629800000
}
}],
"mustNot": [{
"text": {
"query": "documentary",
"path": "genres"
}
}]
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{
"genres": [ "Action", "Adventure", "Sci-Fi" ],
"title": "Terminator Genisys",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama", "Music" ],
"title": "Magic Mike XXL",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama" ],
"title": "Home Care",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Drama", "Mystery", "Sci-Fi" ],
"title": "Pig",
"released": ISODate("2015-07-02T00:00:00.000Z"),
"score": 1.9681909084320068
},
{
"genres": [ "Drama", "History", "Romance" ],
"title": "Gold Coast",
"released": ISODate("2015-07-02T00:00:00.000Z"),
"score": 1.9681909084320068
},
{
"genres": [ "Animation", "Family" ],
"title": "Zarafa",
"released": ISODate("2015-07-03T00:00:00.000Z"),
"score": 1.9383430480957031
}
]

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

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 example uses the compound operator with subqueries to search for movies between the years 2010 to 2015. The query uses the following clauses:

  • A must clause to search for movies released between 2015-01-01 and 2015-12-31

  • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

The query includes a $limit stage to limit the output to 6 results and a $project stage to:

  • Exclude all fields except title, released, and genres fields

  • 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": "date-range-tutorial",
"compound": {
"must": [{
"range": {
"path": "released",
"gt": ISODate("2015-01-01T00:00:00.000Z"),
"lt": ISODate("2015-12-31T00:00:00.000Z")
}
}],
"should": [{
"near": {
"path": "released",
"origin": ISODate("2015-07-01T00:00:00.000+00:00"),
"pivot": 2629800000
}
}]
}
}
$limit
6
$project
{
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"score": {
"$meta": "searchScore"
}
}

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

{
"genres": [ "Action", "Adventure", "Sci-Fi" ],
"title": "Terminator Genisys",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama", "Music" ],
"title": "Magic Mike XXL",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Documentary", "Biography", "Drama" ],
"title": "Mala Mala",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama" ],
"title": "Home Care",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Documentary", "News" ],
"title": "Bitcoin: The End of Money as We Know It",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Drama", "Mystery", "Sci-Fi" ],
"title": "Pig",
"released": ISODate("2015-07-02T00:00:00.000Z"),
"score": 1.9681909084320068
}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

4

The following example adds on to the previous example.

In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

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": "date-range-tutorial",
"compound": {
"must": [{
"range": {
"path": "released",
"gt": ISODate("2015-01-01T00:00:00.000Z"),
"lt": ISODate("2015-12-31T00:00:00.000Z")
}
}],
"should": [{
"near": {
"path": "released",
"origin": ISODate("2015-07-01T00:00:00.000+00:00"),
"pivot": 2629800000
}
}],
"mustNot": [{
"text": {
"query": "documentary",
"path": "genres"
}
}]
}
}
$limit
6
$project
{
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"score": {
"$meta": "searchScore"
}
}

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

{
"genres": [ "Action", "Adventure", "Sci-Fi" ],
"title": "Terminator Genisys",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama", "Music" ],
"title": "Magic Mike XXL",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Comedy", "Drama" ],
"title": "Home Care",
"released": ISODate("2015-07-01T00:00:00.000Z"),
"score": 2
},
{
"genres": [ "Drama", "Mystery", "Sci-Fi" ],
"title": "Pig",
"released": ISODate("2015-07-02T00:00:00.000Z"),
"score": 1.9681909084320068
},
{
"genres": [ "Drama", "History", "Romance" ],
"title": "Gold Coast",
"released": ISODate("2015-07-02T00:00:00.000Z"),
"score": 1.9681909084320068
},
{
"genres": [ "Animation", "Family" ],
"title": "Zarafa",
"released": ISODate("2015-07-03T00:00:00.000Z"),
"score": 1.9383430480957031
}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

1
  1. Create a new directory called date-range-example and initialize your project with the dotnet new command.

    mkdir date-range-example
    cd date-range-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.

    • Uses the following compound operator clauses to query the collection:

      • A must clause to search for movies released between 2015-01-01 and 2015-12-31

      • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

      The query includes a $limit stage to limit the output to 6 results and a $project stage to:

      • Exclude all fields except title, released, and genres fields

      • 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 DateRangeExample
    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 // declare data for compound query
    23 var startDate = new DateTime(2015, 01, 01, 0, 0, 0, DateTimeKind.Utc);
    24 var endDate = new DateTime(2015, 12, 31, 0, 0, 0, DateTimeKind.Utc);
    25 var nearDate = new DateTime(2015, 07, 01, 0, 0, 0, DateTimeKind.Utc);
    26
    27 // define and run pipeline
    28 var results = moviesCollection.Aggregate()
    29 .Search(Builders<MovieDocument>.Search.Compound()
    30 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate)))
    31 .Should(Builders<MovieDocument>.Search.Near(movie => movie.Released, nearDate, 2629800000)),
    32 indexName: "date-range-tutorial")
    33 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    34 .Include(movie => movie.Genres)
    35 .Include(movie => movie.Released)
    36 .Include(movie => movie.Title)
    37 .Exclude(movie => movie.Id)
    38 .MetaSearchScore(movie => movie.Score))
    39 .Limit(6)
    40 .ToList();
    41
    42 // print results
    43 foreach (var movie in results)
    44 {
    45 Console.WriteLine(movie.ToJson());
    46 }
    47 }
    48}
    49
    50[BsonIgnoreExtraElements]
    51public class MovieDocument
    52{
    53 [BsonIgnoreIfDefault]
    54 public ObjectId Id { get; set; }
    55 public string [] Genres { get; set; }
    56 public DateTime Released { get; set; }
    57 public string Title { get; set; }
    58 public double Score { get; set; }
    59}
  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. Compile and run the Program.cs file.

    dotnet run date-range-example.csproj
    { "genres" : ["Action", "Adventure", "Sci-Fi"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Terminator Genisys", "score" : 2.0 }
    { "genres" : ["Comedy", "Drama", "Music"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Magic Mike XXL", "score" : 2.0 }
    { "genres" : ["Documentary", "Biography", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Mala Mala", "score" : 2.0 }
    { "genres" : ["Comedy", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Home Care", "score" : 2.0 }
    { "genres" : ["Documentary", "News"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Bitcoin: The End of Money as We Know It", "score" : 2.0 }
    { "genres" : ["Drama", "Mystery", "Sci-Fi"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Pig", "score" : 1.9681909084320068 }

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

3
  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.

    • Adds on to the previous example.

      In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

    • 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 DateRangeComplexExample
    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 // declare data for compound query
    23 var startDate = new DateTime(2015, 01, 01, 0, 0, 0, DateTimeKind.Utc);
    24 var endDate = new DateTime(2015, 12, 31, 0, 0, 0, DateTimeKind.Utc);
    25 var nearDate = new DateTime(2015, 07, 01, 0, 0, 0, DateTimeKind.Utc);
    26
    27 // define and run pipeline
    28 var results = moviesCollection.Aggregate()
    29 .Search(Builders<MovieDocument>.Search.Compound()
    30 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate)))
    31 .Should(Builders<MovieDocument>.Search.Near(movie => movie.Released, nearDate, 2629800000))
    32 .MustNot(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Documentary")),
    33 indexName: "date-range-tutorial")
    34 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    35 .Include(movie => movie.Genres)
    36 .Include(movie => movie.Released)
    37 .Include(movie => movie.Title)
    38 .Exclude(movie => movie.Id)
    39 .MetaSearchScore(movie => movie.Score))
    40 .Limit(6)
    41 .ToList();
    42
    43 // print results
    44 foreach (var movie in results)
    45 {
    46 Console.WriteLine(movie.ToJson());
    47 }
    48 }
    49}
    50
    51[BsonIgnoreExtraElements]
    52public class MovieDocument
    53{
    54 [BsonIgnoreIfDefault]
    55 public ObjectId Id { get; set; }
    56 public string [] Genres { get; set; }
    57 public DateTime Released { get; set; }
    58 public string Title { get; set; }
    59 public double Score { get; set; }
    60}
  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. Compile and run the Program.cs file.

    dotnet run date-range-example.csproj
    { "genres" : ["Action", "Adventure", "Sci-Fi"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Terminator Genisys", "score" : 2.0 }
    { "genres" : ["Comedy", "Drama", "Music"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Magic Mike XXL", "score" : 2.0 }
    { "genres" : ["Comedy", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Home Care", "score" : 2.0 }
    { "genres" : ["Drama", "Mystery", "Sci-Fi"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Pig", "score" : 1.9681909084320068 }
    { "genres" : ["Drama", "History", "Romance"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Gold Coast", "score" : 1.9681909084320068 }
    { "genres" : ["Animation", "Family"], "released" : ISODate("2015-07-03T00:00:00Z"), "title" : "Zarafa", "score" : 1.9383430480957031 }

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

1
  1. Create a file named date-range.go.

  2. Copy and paste the following code into the date-range.go file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Uses the following compound operator clauses to query the collection:

      • A must clause to search for movies released between 2015-01-01 and 2015-12-31

      • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

      The query includes a $limit stage to limit the output to 6 results and a $project stage to:

      • Exclude all fields except title, released, and genres fields

      • 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": "date-range-tutorial",
    27 "compound": bson.M{
    28 "must": bson.M{
    29 "range": bson.M{
    30 "path": "released",
    31 "gt": time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC),
    32 "lt": time.Date(2015, time.December, 31, 0, 0, 0, 0, time.UTC),
    33 }},
    34 "should": bson.D{
    35 {"near", bson.M{
    36 "path": "released",
    37 "origin": time.Date(2015, time.July, 1, 0, 0, 0, 0, time.UTC),
    38 "pivot": 2629800000,
    39 }}},
    40 }}}}
    41 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    42 limitStage := bson.D{{"$limit", 6}}
    43
    44 // run pipeline
    45 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage, limitStage})
    46 if err != nil {
    47 panic(err)
    48 }
    49
    50 // print results
    51 var results []bson.D
    52 if err = cursor.All(context.TODO(), &results); err != nil {
    53 panic(err)
    54 }
    55 for _, result := range results {
    56 fmt.Println(result)
    57 }
    58}
  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 following command to query your collection:

    go run date-range.go
    [{genres [Action Adventure Sci-Fi]} {title Terminator Genisys} {released 1435708800000} {score 2}]
    [{genres [Comedy Drama Music]} {title Magic Mike XXL} {released 1435708800000} {score 2}]
    [{genres [Documentary Biography Drama]} {title Mala Mala} {released 1435708800000} {score 2}]
    [{genres [Comedy Drama]} {title Home Care} {released 1435708800000} {score 2}]
    [{genres [Documentary News]} {title Bitcoin: The End of Money as We Know It} {released 1435708800000} {score 2}]
    [{genres [Drama Mystery Sci-Fi]} {title Pig} {released 1435795200000} {score 1.9681909084320068}]

    For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

2
  1. Create a file named date-range-complex.go.

  2. Copy and paste the following code into the date-range-complex.go file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Adds on to the previous example.

      In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

    • 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": "date-range-tutorial",
    27 "compound": bson.M{
    28 "must": bson.M{
    29 "range": bson.M{
    30 "path": "released",
    31 "gt": time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC),
    32 "lt": time.Date(2015, time.December, 31, 0, 0, 0, 0, time.UTC),
    33 }},
    34 "should": bson.D{
    35 {"near", bson.M{
    36 "path": "released",
    37 "origin": time.Date(2015, time.July, 1, 0, 0, 0, 0, time.UTC),
    38 "pivot": 2629800000,
    39 }}},
    40 "mustNot": bson.D{
    41 {"text", bson.M{
    42 "path": "genres", "query": "Documentary",
    43 }}},
    44 }}}}
    45 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    46 limitStage := bson.D{{"$limit", 6}}
    47
    48 // run pipeline
    49 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage, limitStage})
    50 if err != nil {
    51 panic(err)
    52 }
    53
    54 // print results
    55 var results []bson.D
    56 if err = cursor.All(context.TODO(), &results); err != nil {
    57 panic(err)
    58 }
    59 for _, result := range results {
    60 fmt.Println(result)
    61 }
    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 following command to query your collection:

    go run date-range-complex.go
    [{genres [Action Adventure Sci-Fi]} {title Terminator Genisys} {released 1435708800000} {score 2}]
    [{genres [Comedy Drama Music]} {title Magic Mike XXL} {released 1435708800000} {score 2}]
    [{genres [Comedy Drama]} {title Home Care} {released 1435708800000} {score 2}]
    [{genres [Drama Mystery Sci-Fi]} {title Pig} {released 1435795200000} {score 1.9681909084320068}]
    [{genres [Drama History Romance]} {title Gold Coast} {released 1435795200000} {score 1.9681909084320068}]
    [{genres [Animation Family]} {title Zarafa} {released 1435881600000} {score 1.9383430480957031}]

    For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

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 DateRange.java.

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

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Uses the following compound operator clauses to query the collection:

      • A must clause to search for movies released between 2015-01-01 and 2015-12-31

      • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

      The query includes a $limit stage to limit the output to 6 results and a $project stage to:

      • Exclude all fields except title, released, and genres fields

      • 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 DateRange {
    17 public static void main( String[] args ) {
    18 // define clauses
    19 List<Document> mustClauses =
    20 List.of( new Document(
    21 "range", new Document("path", "released")
    22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z")))
    23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z")))));
    24 List<Document> shouldClauses =
    25 List.of(
    26 new Document(
    27 "near",
    28 new Document("pivot", 2629800000L)
    29 .append("path", "released")
    30 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00")))));
    31 // define query
    32 Document agg =
    33 new Document( "$search",
    34 new Document("index", "date-range-tutorial")
    35 .append( "compound",
    36 new Document().append("must", mustClauses)
    37 .append("should", shouldClauses)));
    38 // specify connection
    39 String uri = "<connection-string>";
    40
    41 // establish connection and set namespace
    42 try (MongoClient mongoClient = MongoClients.create(uri)) {
    43 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    44 MongoCollection<Document> collection = database.getCollection("movies");
    45
    46 // run query and print results
    47 collection.aggregate(Arrays.asList(agg,
    48 project(fields(
    49 excludeId(),
    50 include("title", "released", "genres"),
    51 computed("score", new Document("$meta", "searchScore")))),
    52 limit(6)))
    53 .forEach(doc -> System.out.println(doc.toJson()));
    54 }
    55 }
    56}

    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 DateRange.java file.

    javac DateRange.java
    java DateRange
    {"genres": ["Action", "Adventure", "Sci-Fi"], "title": "Terminator Genisys", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Comedy", "Drama", "Music"], "title": "Magic Mike XXL", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Documentary", "Biography", "Drama"], "title": "Mala Mala", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Comedy", "Drama"], "title": "Home Care", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Documentary", "News"], "title": "Bitcoin: The End of Money as We Know It", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Drama", "Mystery", "Sci-Fi"], "title": "Pig", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

3
  1. Create a file named DateRangeComplex.java.

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

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Adds on to the previous example.

      In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

    • 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 DateRangeComplex {
    17 public static void main( String[] args ) {
    18 // define clauses
    19 List<Document> mustClauses =
    20 List.of( new Document(
    21 "range", new Document("path", "released")
    22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z")))
    23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z")))));
    24 List<Document> shouldClauses =
    25 List.of(
    26 new Document(
    27 "near",
    28 new Document("pivot", 2629800000L)
    29 .append("path", "released")
    30 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00")))));
    31 List<Document> mustNotClauses =
    32 List.of(
    33 new Document(
    34 "text",
    35 new Document("query", "Documentary")
    36 .append("path", "genres")));
    37 // define query
    38 Document agg =
    39 new Document( "$search",
    40 new Document("index", "date-range-tutorial")
    41 .append( "compound",
    42 new Document().append("must", mustClauses)
    43 .append("should", shouldClauses)
    44 .append("mustNot", mustNotClauses)));
    45 // specify connection
    46 String uri = "<connection-string>";
    47
    48 // establish connection and set namespace
    49 try (MongoClient mongoClient = MongoClients.create(uri)) {
    50 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    51 MongoCollection<Document> collection = database.getCollection("movies");
    52
    53 // run query and print results
    54 collection.aggregate(Arrays.asList(agg,
    55 project(fields(
    56 excludeId(),
    57 include("title", "released", "genres"),
    58 computed("score", new Document("$meta", "searchScore")))),
    59 limit(6)))
    60 .forEach(doc -> System.out.println(doc.toJson()));
    61 }
    62 }
    63}

    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 DateRangeComplex.java file.

    javac DateRangeComplex.java
    java DateRangeComplex
    {"genres": ["Action", "Adventure", "Sci-Fi"], "title": "Terminator Genisys", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Comedy", "Drama", "Music"], "title": "Magic Mike XXL", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Comedy", "Drama"], "title": "Home Care", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0}
    {"genres": ["Drama", "Mystery", "Sci-Fi"], "title": "Pig", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068}
    {"genres": ["Drama", "History", "Romance"], "title": "Gold Coast", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068}
    {"genres": ["Animation", "Family"], "title": "Zarafa", "released": {"$date": "2015-07-03T00:00:00Z"}, "score": 1.9383430480957031}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

1
mongodb-driver-kotlin-coroutine
4.10.0 or higher version
2
  1. Create a file named DateRange.kt.

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

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Uses the following compound operator clauses to query the collection:

      • A must clause to search for movies released between 2015-01-01 and 2015-12-31

      • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

      The query includes a $limit stage to limit the output to 6 results and a $project stage to:

      • Exclude all fields except title, released, and genres fields

      • 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 clauses
    19 val mustClauses = listOf(
    20 Document(
    21 "range", Document("path", "released")
    22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z")))
    23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z")))
    24 )
    25 )
    26
    27 val shouldClauses = listOf(
    28 Document(
    29 "near",
    30 Document("pivot", 2629800000L)
    31 .append("path", "released")
    32 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00")))
    33 )
    34 )
    35
    36 // define query
    37 val agg = Document(
    38 "\$search",
    39 Document("index", "date-range-tutorial")
    40 .append(
    41 "compound",
    42 Document().append("must", mustClauses)
    43 .append("should", shouldClauses)
    44 )
    45 )
    46
    47 // run query and print results
    48 val resultsFlow = collection.aggregate<Document>(
    49 listOf(
    50 agg,
    51 limit(6),
    52 project(fields(
    53 excludeId(),
    54 include("title", "released", "genres"),
    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 DateRange.kt file.

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

    Document{{genres=[Action, Adventure, Sci-Fi], title=Terminator Genisys, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Comedy, Drama, Music], title=Magic Mike XXL, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Documentary, News], title=Bitcoin: The End of Money as We Know It, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Documentary, Biography, Drama], title=Mala Mala, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Comedy, Drama], title=Home Care, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Drama, Mystery, Sci-Fi], title=Pig, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

3
  1. Create a file named DateRangeComplex.kt.

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

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Adds on to the previous example.

      In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

    • 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 clauses
    19 val mustClauses = listOf(
    20 Document(
    21 "range", Document("path", "released")
    22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z")))
    23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z")))
    24 )
    25 )
    26
    27 val shouldClauses = listOf(
    28 Document(
    29 "near",
    30 Document("pivot", 2629800000L)
    31 .append("path", "released")
    32 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00")))
    33 )
    34 )
    35
    36 val mustNotClauses = listOf(
    37 Document(
    38 "text",
    39 Document("query", "Documentary")
    40 .append("path", "genres")
    41 )
    42 )
    43
    44 // define query
    45 val agg = Document(
    46 "\$search",
    47 Document("index", "date-range-tutorial")
    48 .append(
    49 "compound",
    50 Document().append("must", mustClauses)
    51 .append("should", shouldClauses)
    52 .append("mustNot", mustNotClauses)
    53 )
    54 )
    55
    56 // run query and print results
    57 val resultsFlow = collection.aggregate<Document>(
    58 listOf(
    59 agg,
    60 limit(6),
    61 project(fields(
    62 excludeId(),
    63 include("title", "released", "genres"),
    64 computed("score", Document("\$meta", "searchScore"))
    65 ))
    66 )
    67 )
    68 resultsFlow.collect { println(it) }
    69 }
    70 mongoClient.close()
    71}
  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 DateRangeComplex.kt file.

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

    Document{{genres=[Action, Adventure, Sci-Fi], title=Terminator Genisys, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Comedy, Drama, Music], title=Magic Mike XXL, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Comedy, Drama], title=Home Care, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}}
    Document{{genres=[Drama, Mystery, Sci-Fi], title=Pig, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}}
    Document{{genres=[Drama, History, Romance], title=Gold Coast, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}}
    Document{{genres=[Drama], title=Jackie & Ryan, released=Thu Jul 02 20:00:00 EDT 2015, score=1.9383430480957031}}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

1
  1. Create a file named date-range.js.

  2. Copy and paste the following code into the date-range.js file.

    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.

    • Uses the following compound operator clauses to query the collection:

      • A must clause to search for movies released between 2015-01-01 and 2015-12-31

      • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

      The query includes a $limit stage to limit the output to 6 results and a $project stage to:

      • Exclude all fields except title, released, and genres fields

      • Add a field named score

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

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    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: 'date-range-tutorial',
    21 compound: {
    22 must: [{ range: { path: "released", gt: new Date("2015-01-01T00:00:00.000Z"), lt: new Date("2015-12-31T00:00:00.000Z") }}],
    23 should: [{ near: { path: "released", origin: new Date("2015-07-01T00:00:00.000Z"), pivot: 2629800000 }}]}}},
    24 { $project: {_id: 0, title: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}},
    25 { $limit: 6 }
    26 ];
    27
    28 // run pipeline
    29 const result = await coll.aggregate(agg);
    30
    31 // print results
    32 await result.forEach((doc) => console.log(doc));
    33 } finally {
    34 await client.close();
    35 }
    36}
    37run().catch(console.dir);
  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 following command to query your collection:

    node date-range.js
    {
    genres: [ 'Action', 'Adventure', 'Sci-Fi' ],
    title: 'Terminator Genisys',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Comedy', 'Drama', 'Music' ],
    title: 'Magic Mike XXL',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Documentary', 'Biography', 'Drama' ],
    title: 'Mala Mala',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Comedy', 'Drama' ],
    title: 'Home Care',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Documentary', 'News' ],
    title: 'Bitcoin: The End of Money as We Know It',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Drama', 'Mystery', 'Sci-Fi' ],
    title: 'Pig',
    released: 2015-07-02T00:00:00.000Z,
    score: 1.9681909084320068
    }

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

2
  1. Create a file named date-range-complex.js.

  2. Copy and paste the following code into the date-range-complex.js file.

    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.

    • Adds on to the previous example.

      In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

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

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    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: 'date-range-tutorial',
    21 compound: {
    22 must: [{ range: { path: "released", gt: new Date("2015-01-01T00:00:00.000Z"), lt: new Date("2015-12-31T00:00:00.000Z") }}],
    23 should: [{ near: { path: "released", origin: new Date("2015-07-01T00:00:00.000Z"), pivot: 2629800000 }}],
    24 mustNot: [{ text: { path: "genres", query: "Documentary"} }]}}},
    25 { $project: {_id: 0, title: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}},
    26 { $limit: 6 }
    27 ];
    28
    29 // run pipeline
    30 const result = await coll.aggregate(agg);
    31
    32 // print results
    33 await result.forEach((doc) => console.log(doc));
    34 } finally {
    35 await client.close();
    36 }
    37}
    38run().catch(console.dir);
  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 following command to query your collection:

    node date-range-complex.js
    {
    genres: [ 'Action', 'Adventure', 'Sci-Fi' ],
    title: 'Terminator Genisys',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Comedy', 'Drama', 'Music' ],
    title: 'Magic Mike XXL',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Comedy', 'Drama' ],
    title: 'Home Care',
    released: 2015-07-01T00:00:00.000Z,
    score: 2
    }
    {
    genres: [ 'Drama', 'Mystery', 'Sci-Fi' ],
    title: 'Pig',
    released: 2015-07-02T00:00:00.000Z,
    score: 1.9681909084320068
    }
    {
    genres: [ 'Drama', 'History', 'Romance' ],
    title: 'Gold Coast',
    released: 2015-07-02T00:00:00.000Z,
    score: 1.9681909084320068
    }
    {
    genres: [ 'Animation', 'Family' ],
    title: 'Zarafa',
    released: 2015-07-03T00:00:00.000Z,
    score: 1.9383430480957031
    }

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

1
  1. Create a file named date-range.py.

  2. Copy and paste the following code into the date-range.py file.

    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.

    • Uses the following compound operator clauses to query the collection:

      • A must clause to search for movies released between 2015-01-01 and 2015-12-31

      • A should clause to specify preference for movies released near 2012-07-01, with a pivot distance of 1 month

      The query includes a $limit stage to limit the output to 6 results and a $project stage to:

      • Exclude all fields except title, released, and genres fields

      • Add a field named score

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

    1import pymongo
    2import datetime
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient("<connection-string>")
    6
    7# define pipeline
    8pipeline = [
    9 {"$search": {
    10 "index": "date-range-tutorial",
    11 "compound": {
    12 "must": [{"range": {"path": "released", "gt": datetime.datetime(2015,1,1,0,0,0), "lt": datetime.datetime(2015,12,31,0,0,0)}}],
    13 "should": [{"near": {"path": "released", "origin": datetime.datetime(2015, 7, 1, 0, 0, 0, 0), "pivot": 2629800000}}]}}},
    14 {"$limit": 6},
    15 {"$project": {"_id": 0, "title": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}}
    16]
    17# run pipeline
    18result = client["sample_mflix"]["movies"].aggregate(pipeline)
    19
    20# print results
    21for i in result:
    22 print(i)
  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 following command to query your collection:

    python date-range.py
    {'genres': ['Action', 'Adventure', 'Sci-Fi'], 'title': 'Terminator Genisys', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Comedy', 'Drama', 'Music'], 'title': 'Magic Mike XXL', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Documentary', 'Biography', 'Drama'], 'title': 'Mala Mala', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Comedy', 'Drama'], 'title': 'Home Care', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Documentary', 'News'], 'title': 'Bitcoin: The End of Money as We Know It', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Drama', 'Mystery', 'Sci-Fi'], 'title': 'Pig', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

2
  1. Create a file named date-range-complex.py.

  2. Copy and paste the following code into the date-range-complex.py file.

    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.

    • Adds on to the previous example.

      In addition to the must and should clauses, this query also includes a mustNot clause to specify that movies in the documentary genre must not be included in the results.

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

    1import pymongo
    2import datetime
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient("<connection-string>")
    6
    7# define pipeline
    8pipeline = [
    9 {"$search": {
    10 "index": "date-range-tutorial",
    11 "compound": {
    12 "must": [{"range": {"path": "released", "gt": datetime.datetime(2015,1,1,0,0,0), "lt": datetime.datetime(2015,12,31,0,0,0)}}],
    13 "should": [{"near": {"path": "released", "origin": datetime.datetime(2015, 7, 1, 0, 0, 0, 0), "pivot": 2629800000}}],
    14 "mustNot": [{"text": {"path": "genres", "query": "Documentary"}}]}}},
    15 {"$limit": 6},
    16 {"$project": {"_id": 0, "title": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}}
    17]
    18# run pipeline
    19result = client["sample_mflix"]["movies"].aggregate(pipeline)
    20
    21# print results
    22for i in result:
    23 print(i)
  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 following command to query your collection:

    python date-range-complex.py
    {'genres': ['Action', 'Adventure', 'Sci-Fi'], 'title': 'Terminator Genisys', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Comedy', 'Drama', 'Music'], 'title': 'Magic Mike XXL', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Comedy', 'Drama'], 'title': 'Home Care', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0}
    {'genres': ['Drama', 'Mystery', 'Sci-Fi'], 'title': 'Pig', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068}
    {'genres': ['Drama', 'History', 'Romance'], 'title': 'Gold Coast', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068}
    {'genres': ['Animation', 'Family'], 'title': 'Zarafa', 'released': datetime.datetime(2015, 7, 3, 0, 0), 'score': 1.9383430480957031}

For the query, the top results are in the month of July because the should clause specified a preference for movies near July.

Back

Array of Objects

Next

Date and Numeric String Queries