Docs Menu
Docs Home
/
MongoDB Atlas
/ /

How to Run Atlas Search String Queries Against Date and Numeric Fields

On this page

  • Create a Materialized View on the Collection
  • Create Atlas Search Indexes on Fields in the Materialized View
  • Perform Text Search on Converted Fields

This tutorial describes how to run Atlas Search queries against string, date, and number fields in the sample_airbnb.listingsAndReviews collection. You will create a materialized view that stores the numeric and date field values as strings. You will then create an Atlas Search index on the materialized view and run queries against these string fields using the queryString and autocomplete operators. This tutorial takes you through the following steps:

  1. Create a materialized view on the sample_airbnb.listingsAndReviews collection name, property_type, last_scraped, and accomodates fields.

  2. Set up dynamic and static Atlas Search indexes on the materialized view.

  3. Run Atlas Search queries against the fields in the materialized view using the queryString and autocomplete operators to search for properties.

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, you will create a materialized view named airbnb-mat-view for name, property_type, last_scraped, accomodates, and maximum_nights fields in the airbnb_listingsAndReviews collection. The materialized view allows you to take the numeric and date fields in the source collection and store them as string fields in the materialized view.

1

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

2
  1. Run the following command to verify that the database exists in your cluster:

    show dbs
    sample_airbnb 55.3 MB
    sample_analytics 9.59 MB
    sample_geospatial 1.43 MB
    sample_guides 41 kB
    sample_mflix 51.1 MB
    sample_restaurants 6.95 MB
    sample_supplies 1.21 MB
    sample_training 55.5 MB
    sample_weatherdata 2.89 MB
    admin 348 kB
    local 2.1 GB
  2. Run the following command to switch to the sample_airbnb database.

    use sample_airbnb
    switched to db sample_airbnb
3

To create a materialized view, run the following query. The query specifies the following aggregation pipeline stages:

  • $project: In this stage, the query does the following:

    • Converts the last_scraped date object to a string in the format YYYY-MM-DD using $dateToString.

    • Includes name and property_type string fields.

    • Converts accomodates number field to a string using $toString.

    • Converts maximum_nights number field to a string using $toString.

  • $merge: In this stage, the query writes the output fields from the $project stage to a materialized view named airbnb_mat_view.

    db.listingsAndReviews.aggregate( [
    {
    $project: {
    lastScrapedDate: { $dateToString: { format: "%Y-%m-%d", date: "$last_scraped" } },
    propertyName: "$name",
    propertyType: "$property_type",
    accommodatesNumber: { $toString: "$accommodates" },
    maximumNumberOfNights: { $toString: "$maximum_nights" }
    }
    },
    { $merge: { into: "airbnb_mat_view", whenMatched: "replace" } }
    ] )
4

To verify, run the following command:

db.airbnb_mat_view.findOne()
{
_id: '10006546',
lastScrapedDate: '2019-02-16',
propertyName: 'Ribeira Charming Duplex',
propertyType: 'House',
accommodatesNumber: '8',
maximumNumberOfNights: '30'
}

In this section, you will create Atlas Search indexes on the lastScrapedDate, name, propertyType, accommodatesNumber, and maximumNumberOfNights fields for running queries against these fields.

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 Visual Editor.

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

5
  1. In the Index Name field, enter date-number-fields-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_airbnb database, and select the airbnb_mat_view collection.

6

You can create one of the following indexes:

  • Index that uses dynamic mappings for running queries using the queryString operator. You can't run queries using the autocomplete operator if your index definition uses only dynamic mappings.

  • Index that uses static mappings for running queries using autocomplete operator. You can't run queries using the queryString operator against fields indexed as type autocomplete.

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

  1. Click Next.

  2. Click Create Search Index.

  1. Review the index definition.

    Your index definition should look similar to the following:

    {
    "mappings": {
    "dynamic": true
    }
    }
  2. Click Next.

  3. Click Create Search Index.

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

  1. Click Next

  2. Click Refine Your Index.

  3. Click Add Field in the Field Mappings section.

  4. Select accommodatesNumber from the Field Name dropdown.

  5. Click the Data Type dropdown, select Autocomplete from the dropdown, and configure the following fields:

    UI Field Name
    Configuration
    Max Grams
    15
    Min Grams

    1

    Note

    This value is for demonstration purposes only. We don't recommend such a low value because it can result in a very large index.

    Tokenization
    edgeGram
    Fold Diacritics
    true
  6. Click Add to add the field to the Field Mappings table.

  7. Click Add Field in the Field Mappings section and repeat step d to step f to configure the settings for the following fields:

    • lastScrapedDate

    • numberOfNights

  8. Click Save Changes.

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

    {
    "mappings": {
    "dynamic": false,
    "fields": {
    "accommodatesNumber": [
    {
    "dynamic": true,
    "type": "document"
    },
    {
    "minGrams": 1,
    "type": "autocomplete"
    }
    ],
    "lastScrapedDate": [
    {
    "dynamic": true,
    "type": "document"
    },
    {
    "type": "autocomplete"
    }
    ],
    "maximumNumberOfNights": [
    {
    "dynamic": true,
    "type": "document"
    },
    {
    "minGrams": 1,
    "type": "autocomplete"
    }
    ]
    }
    }
    }
  2. Click Next.

7

Note

The You're All Set! modal window appears to let you know your index is building.

8

You can run queries against the numeric and date fields that were converted to strings. This tutorial uses queryString and autocomplete operators to search for properties. The query uses the following pipeline stages:

  • $search stage to search the collection

  • $limit stage to limit the output to 5 results

  • $project stage to exclude _id

In this section, you will connect to your Atlas cluster and run the sample queries using the operator against the fields in the airbnb_mat_view collection.

Note

You can't run near or range queries against the date and number fields that were converted to strings in your materialized view.


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


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_airbnb
switched to db sample_airbnb
3

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
1 [
2 {
3 lastScrapedDate: '2019-03-06',
4 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
5 propertyType: 'Condominium',
6 accommodatesNumber: '4'
7 },
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Makaha Valley Paradise with OceanView',
11 propertyType: 'Condominium',
12 accommodatesNumber: '4'
13 },
14 {
15 lastScrapedDate: '2019-03-06',
16 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!',
17 propertyType: 'Condominium',
18 accommodatesNumber: '4'
19 },
20 {
21 lastScrapedDate: '2019-03-06',
22 propertyName: 'Tropical Jungle Oasis',
23 propertyType: 'Condominium',
24 accommodatesNumber: '4'
25 },
26 {
27 lastScrapedDate: '2019-02-11',
28 propertyName: 'Hospede-se com acesso fácil.',
29 propertyType: 'Condominium',
30 accommodatesNumber: '4'
31 }
32 ]
33

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
1 [
2 {
3 lastScrapedDate: '2019-02-11',
4 propertyName: '2017 , férias no Rio',
5 propertyType: 'House',
6 accommodatesNumber: '2',
7 maximumNumberOfNights: '30'
8 },
9 {
10 lastScrapedDate: '2019-03-07',
11 propertyName: 'Newly renovated home',
12 propertyType: 'House',
13 accommodatesNumber: '2',
14 maximumNumberOfNights: '30'
15 },
16 {
17 lastScrapedDate: '2019-02-18',
18 propertyName: 'Vintage House For Rent',
19 propertyType: 'House',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '30'
22 },
23 {
24 lastScrapedDate: '2019-02-18',
25 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev',
26 propertyType: 'House',
27 accommodatesNumber: '2',
28 maximumNumberOfNights: '30'
29 },
30 {
31 lastScrapedDate: '2019-02-16',
32 propertyName: '22 Oporto Guesthouse Cordoaria',
33 propertyType: 'House',
34 accommodatesNumber: '2',
35 maximumNumberOfNights: '30'
36 }
37

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "lastScrapedDate",
"query": "2"
}
},
{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "1"
}
}]
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
[
{
lastScrapedDate: '2019-02-11',
propertyName: 'Horto flat with small garden',
propertyType: 'Apartment',
accommodatesNumber: '4',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-03-06',
propertyName: 'Private Room in Bushwick',
propertyType: 'Apartment',
accommodatesNumber: '1',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-02-11',
propertyName: 'Apt Linda Vista Lagoa - Rio',
propertyType: 'Apartment',
accommodatesNumber: '2',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-02-18',
propertyName: 'Charming Flat in Downtown Moda',
propertyType: 'House',
accommodatesNumber: '6',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-02-11',
propertyName: "Catete's Colonial Big Hause Room B",
propertyType: 'House',
accommodatesNumber: '8',
maximumNumberOfNights: '1125'
}
]

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "3"
}
},
{
"autocomplete": {
"path": "accommodatesNumber",
"query": "2"
}
}]
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
[
{
lastScrapedDate: '2019-03-06',
propertyName: 'Ocean View Waikiki Marina w/prkg',
propertyType: 'Condominium',
accommodatesNumber: '2',
maximumNumberOfNights: '365'
},
{
lastScrapedDate: '2019-03-07',
propertyName: 'New York City - Upper West Side Apt',
propertyType: 'Apartment',
accommodatesNumber: '2',
maximumNumberOfNights: '360'
},
{
lastScrapedDate: '2019-03-07',
propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)',
propertyType: 'Apartment',
accommodatesNumber: '2',
maximumNumberOfNights: '30'
},
{
lastScrapedDate: '2019-03-07',
propertyName: 'Private Room (2) in Guest House at Coogee Beach',
propertyType: 'House',
accommodatesNumber: '2',
maximumNumberOfNights: '365'
},
{
lastScrapedDate: '2019-03-06',
propertyName: '~Ao Lele~ Flying Cloud',
propertyType: 'Treehouse',
accommodatesNumber: '2',
maximumNumberOfNights: '30'
}
]
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_airbnb database, then click the airbnb_mat_view collection.

3

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

Pipeline Stage
Query
$search
{
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
}
}
$limit
{
5
}
$project
{
"_id": 0
}

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

1 [
2 {
3 lastScrapedDate: '2019-03-06',
4 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
5 propertyType: 'Condominium',
6 accommodatesNumber: '4'
7 },
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Makaha Valley Paradise with OceanView',
11 propertyType: 'Condominium',
12 accommodatesNumber: '4'
13 },
14 {
15 lastScrapedDate: '2019-03-06',
16 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!',
17 propertyType: 'Condominium',
18 accommodatesNumber: '4'
19 },
20 {
21 lastScrapedDate: '2019-03-06',
22 propertyName: 'Tropical Jungle Oasis',
23 propertyType: 'Condominium',
24 accommodatesNumber: '4'
25 },
26 {
27 lastScrapedDate: '2019-02-11',
28 propertyName: 'Hospede-se com acesso fácil.',
29 propertyType: 'Condominium',
30 accommodatesNumber: '4'
31 }
32 ]
33

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

Pipeline Stage
Query
$search
{
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
}
}
$limit
{
5
}
$project
{
"_id": 0
}

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

1 [
2 {
3 lastScrapedDate: '2019-02-11',
4 propertyName: '2017 , férias no Rio',
5 propertyType: 'House',
6 accommodatesNumber: '2',
7 maximumNumberOfNights: '30'
8 },
9 {
10 lastScrapedDate: '2019-03-07',
11 propertyName: 'Newly renovated home',
12 propertyType: 'House',
13 accommodatesNumber: '2',
14 maximumNumberOfNights: '30'
15 },
16 {
17 lastScrapedDate: '2019-02-18',
18 propertyName: 'Vintage House For Rent',
19 propertyType: 'House',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '30'
22 },
23 {
24 lastScrapedDate: '2019-02-18',
25 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev',
26 propertyType: 'House',
27 accommodatesNumber: '2',
28 maximumNumberOfNights: '30'
29 },
30 {
31 lastScrapedDate: '2019-02-16',
32 propertyName: '22 Oporto Guesthouse Cordoaria',
33 propertyType: 'House',
34 accommodatesNumber: '2',
35 maximumNumberOfNights: '30'
36 }
37

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

Pipeline Stage
Query
$search
{
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "lastScrapedDate",
"query": "2"
}
},
{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "1"
}
}]
}
}
$limit
{
5
}
$project
{
"_id": 0
}

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

1 [
2 {
3 lastScrapedDate: '2019-02-11',
4 propertyName: 'Horto flat with small garden',
5 propertyType: 'Apartment',
6 accommodatesNumber: '4',
7 maximumNumberOfNights: '1125'
8 },
9 {
10 lastScrapedDate: '2019-03-06',
11 propertyName: 'Private Room in Bushwick',
12 propertyType: 'Apartment',
13 accommodatesNumber: '1',
14 maximumNumberOfNights: '1125'
15 },
16 {
17 lastScrapedDate: '2019-02-11',
18 propertyName: 'Apt Linda Vista Lagoa - Rio',
19 propertyType: 'Apartment',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '1125'
22 },
23 {
24 lastScrapedDate: '2019-02-18',
25 propertyName: 'Charming Flat in Downtown Moda',
26 propertyType: 'House',
27 accommodatesNumber: '6',
28 maximumNumberOfNights: '1125'
29 },
30 {
31 lastScrapedDate: '2019-02-11',
32 propertyName: "Catete's Colonial Big Hause Room B",
33 propertyType: 'House',
34 accommodatesNumber: '8',
35 maximumNumberOfNights: '1125'
36 }
37 ]

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

Pipeline Stage
Query
$search
{
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "3"
}
},
{
"autocomplete": {
"path": "accommodatesNumber",
"query": "2"
}
}]
}
}
$limit
{
5
}
$project
{
"_id": 0
}

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

1[
2 {
3 lastScrapedDate: '2019-03-06',
4 propertyName: 'Ocean View Waikiki Marina w/prkg',
5 propertyType: 'Condominium',
6 accommodatesNumber: '2',
7 maximumNumberOfNights: '365'
8 },
9 {
10 lastScrapedDate: '2019-03-07',
11 propertyName: 'New York City - Upper West Side Apt',
12 propertyType: 'Apartment',
13 accommodatesNumber: '2',
14 maximumNumberOfNights: '360'
15 },
16 {
17 lastScrapedDate: '2019-03-07',
18 propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)',
19 propertyType: 'Apartment',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '30'
22 },
23 {
24 lastScrapedDate: '2019-03-07',
25 propertyName: 'Private Room (2) in Guest House at Coogee Beach',
26 propertyType: 'House',
27 accommodatesNumber: '2',
28 maximumNumberOfNights: '365'
29 },
30 {
31 lastScrapedDate: '2019-03-06',
32 propertyName: '~Ao Lele~ Flying Cloud',
33 propertyType: 'Treehouse',
34 accommodatesNumber: '2',
35 maximumNumberOfNights: '30'
36 }
37]
1
mkdir date-number-to-string-query
cd date-number-to-string-query
dotnet new console
2
dotnet add package MongoDB.Driver
3

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

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

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.QueryString(
25 airbnb => airbnb.propertyType,
26 "(Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"
27 ),
28 indexName: "date-number-fields-tutorial")
29 .Limit(5)
30 .Project<matViewDocument>(Builders<matViewDocument>.Projection
31 .Exclude(airbnb => airbnb.Id))
32 .ToList();
33
34 // print results
35 foreach (var airbnb in results)
36 {
37 Console.WriteLine(airbnb.ToJson());
38 }
39 }
40}
41
42[BsonIgnoreExtraElements]
43public class matViewDocument
44{
45 [BsonIgnoreIfDefault]
46 public string Id { get; set; }
47 public string lastScrapedDate { get; set; }
48 public string propertyName { get; set; }
49 public string propertyType { get; set; }
50 public string accommodatesNumber { get; set; }
51 public string maximumNumberOfNights { get; set; }
52}

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.

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 var ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.QueryString(
25 airbnb => airbnb.propertyType,
26 "House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
27 ),
28 indexName: "date-number-fields-tutorial")
29 .Limit(5)
30 .Project<matViewDocument>(Builders<matViewDocument>.Projection
31 .Exclude(airbnb => airbnb.Id))
32 .ToList();
33
34 // print results
35 foreach (var airbnb in results)
36 {
37 Console.WriteLine(airbnb.ToJson());
38 }
39 }
40}
41
42[BsonIgnoreExtraElements]
43public class matViewDocument
44{
45 [BsonIgnoreIfDefault]
46 public string Id { get; set; }
47 public string lastScrapedDate { get; set; }
48 public string propertyName { get; set; }
49 public string propertyType { get; set; }
50 public string accommodatesNumber { get; set; }
51 public string maximumNumberOfNights { get; set; }
52}

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.

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

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

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.Compound()
25 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.lastScrapedDate, "2"))
26 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.maximumNumberOfNights, "1")),
27 indexName: "date-number-fields-tutorial")
28 .Limit(5)
29 .Project<matViewDocument>(Builders<matViewDocument>.Projection
30 .Exclude(airbnb => airbnb.Id))
31 .ToList();
32
33 // print results
34 foreach (var airbnb in results)
35 {
36 Console.WriteLine(airbnb.ToJson());
37 }
38 }
39}
40
41[BsonIgnoreExtraElements]
42public class matViewDocument
43{
44 [BsonIgnoreIfDefault]
45 public string Id { get; set; }
46 public string lastScrapedDate { get; set; }
47 public string propertyName { get; set; }
48 public string propertyType { get; set; }
49 public string accommodatesNumber { get; set; }
50 public string maximumNumberOfNights { get; set; }
51}

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.

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.Compound()
25 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.maximumNumberOfNights, "3"))
26 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.accommodatesNumber, "2")),
27 indexName: "date-number-fields-tutorial")
28 .Limit(5)
29 .Project<matViewDocument>(Builders<matViewDocument>.Projection
30 .Exclude(airbnb => airbnb.Id))
31 .ToList();
32
33 // print results
34 foreach (var airbnb in results)
35 {
36 Console.WriteLine(airbnb.ToJson());
37 }
38 }
39}
40
41[BsonIgnoreExtraElements]
42public class matViewDocument
43{
44 [BsonIgnoreIfDefault]
45 public string Id { get; set; }
46 public string lastScrapedDate { get; set; }
47 public string propertyName { get; set; }
48 public string propertyType { get; set; }
49 public string accommodatesNumber { get; set; }
50 public string maximumNumberOfNights { get; set; }
51}

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
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Makaha Valley Paradise with OceanView",
11 "propertyType": "Condominium",
12 "accommodatesNumber": "4",
13 "maximumNumberOfNights": "180"
14}
15{
16 "lastScrapedDate": "2019-03-06",
17 "propertyName": "March 2019 availability! Oceanview on Sugar Beach!",
18 "propertyType": "Condominium",
19 "accommodatesNumber": "4",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-03-06",
24 "propertyName": "Tropical Jungle Oasis",
25 "propertyType": "Condominium",
26 "accommodatesNumber": "4",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Hospede-se com acesso fácil.",
32 "propertyType": "Condominium",
33 "accommodatesNumber": "4",
34 "maximumNumberOfNights": "1125"
35}
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "2017 , férias no Rio",
4 "propertyType": "House",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "30"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "Newly renovated home",
11 "propertyType": "House",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "30"
14}
15{
16 "lastScrapedDate": "2019-02-18",
17 "propertyName": "Vintage House For Rent",
18 "propertyType": "House",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "4floor house in Taksim,Taksimde 4katli müstakil ev",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "30"
28}
29{
30 "lastScrapedDate": "2019-02-16",
31 "propertyName": "22 Oporto Guesthouse Cordoaria",
32 "propertyType": "House",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "Horto flat with small garden",
4 "propertyType": "Apartment",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Private Room in Bushwick",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "1",
13 "maximumNumberOfNights": "1125"
14}
15{
16 "lastScrapedDate": "2019-02-11",
17 "propertyName": "Apt Linda Vista Lagoa - Rio",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "Charming Flat in Downtown Moda",
25 "propertyType": "House",
26 "accommodatesNumber": "6",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Catete's Colonial Big Hause Room B",
32 "propertyType": "House",
33 "accommodatesNumber": "8",
34 "maximumNumberOfNights": "1125"
35}
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "Ocean View Waikiki Marina w/prkg",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "365"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "New York City - Upper West Side Apt",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "360"
14}
15{
16 "lastScrapedDate": "2019-03-07",
17 "propertyName": "Sydney Hyde Park City Apartment (checkin from 6am)",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-03-07",
24 "propertyName": "Private Room (2) in Guest House at Coogee Beach",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "365"
28}
29{
30 "lastScrapedDate": "2019-03-06",
31 "propertyName": "~Ao Lele~ Flying Cloud",
32 "propertyType": "Treehouse",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
1
2

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

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 var err error
15 // connect to the Atlas cluster
16 ctx := context.Background()
17 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
18 if err != nil {
19 panic(err)
20 }
21 defer client.Disconnect(ctx)
22 // set namespace
23 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
24 // define pipeline
25 searchStage := bson.D{{"$search", bson.D{
26 {"index", "date-number-fields-tutorial"},
27 {"queryString", bson.D{
28 {"defaultPath", "propertyType"},
29 {"query", "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"},
30 }}}}}
31 limitStage := bson.D{{"$limit", 5}}
32 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
33 // specify the amount of time the operation can run on the server
34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
35 // run pipeline
36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
37 if err != nil {
38 panic(err)
39 }
40 // print results
41 var results []bson.D
42 if err = cursor.All(context.TODO(), &results); err != nil {
43 panic(err)
44 }
45 for _, result := range results {
46 fmt.Println(result)
47 }
48}

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.

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

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 var err error
15 // connect to the Atlas cluster
16 ctx := context.Background()
17 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
18 if err != nil {
19 panic(err)
20 }
21 defer client.Disconnect(ctx)
22 // set namespace
23 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
24 // define pipeline
25 searchStage := bson.D{{"$search", bson.D{
26 {"index", "date-number-fields-tutorial"},
27 {"queryString", bson.D{
28 {"defaultPath", "propertyType"},
29 {"query", "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"},
30 }}}}}
31 limitStage := bson.D{{"$limit", 5}}
32 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
33 // specify the amount of time the operation can run on the server
34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
35 // run pipeline
36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
37 if err != nil {
38 panic(err)
39 }
40 // print results
41 var results []bson.D
42 if err = cursor.All(context.TODO(), &results); err != nil {
43 panic(err)
44 }
45 for _, result := range results {
46 fmt.Println(result)
47 }
48}

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.

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

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
13// define structure of movies collection
14type MovieCollection struct {
15 title string `bson:"Title,omitempty"`
16}
17
18func main() {
19 var err error
20 // connect to the Atlas cluster
21 ctx := context.Background()
22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-tring>"))
23 if err != nil {
24 panic(err)
25 }
26 defer client.Disconnect(ctx)
27 // set namespace
28 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
29 // define pipeline
30 searchStage := bson.D{{"$search", bson.M{
31 "index": "date-number-fields-tutorial",
32 "compound": bson.M{
33 "should": bson.A{
34 bson.M{
35 "autocomplete": bson.M{
36 "path": "lastScrapedDate", "query": "2",
37 },
38 },
39 bson.M{
40 "autocomplete": bson.M{
41 "path": "maximumNumberOfNights", "query": "1",
42 },
43 },
44 },
45 },
46 }}}
47 limitStage := bson.D{{"$limit", 5}}
48 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
49 // specify the amount of time the operation can run on the server
50 opts := options.Aggregate().SetMaxTime(5 * time.Second)
51 // run pipeline
52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
53 if err != nil {
54 panic(err)
55 }
56 // print results
57 var results []bson.D
58 if err = cursor.All(context.TODO(), &results); err != nil {
59 panic(err)
60 }
61 for _, result := range results {
62 fmt.Println(result)
63 }
64}

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.

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

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
13// define structure of movies collection
14type MovieCollection struct {
15 title string `bson:"Title,omitempty"`
16}
17
18func main() {
19 var err error
20 // connect to the Atlas cluster
21 ctx := context.Background()
22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
23 if err != nil {
24 panic(err)
25 }
26 defer client.Disconnect(ctx)
27 // set namespace
28 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
29 // define pipeline
30 searchStage := bson.D{{"$search", bson.M{
31 "index": "date-number-fields-tutorial",
32 "compound": bson.M{
33 "should": bson.A{
34 bson.M{
35 "autocomplete": bson.M{
36 "path": "maximumNumberOfNights", "query": "3",
37 },
38 },
39 bson.M{
40 "autocomplete": bson.M{
41 "path": "accommodatesNumber", "query": "2",
42 },
43 },
44 },
45 },
46 }}}
47 limitStage := bson.D{{"$limit", 5}}
48 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
49 // specify the amount of time the operation can run on the server
50 opts := options.Aggregate().SetMaxTime(5 * time.Second)
51 // run pipeline
52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
53 if err != nil {
54 panic(err)
55 }
56 // print results
57 var results []bson.D
58 if err = cursor.All(context.TODO(), &results); err != nil {
59 panic(err)
60 }
61 for _, result := range results {
62 fmt.Println(result)
63 }
64}

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 date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-03-06}
3 {propertyName LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!}
4 {propertyType Condominium}
5 {accommodatesNumber 4}
6 {maximumNumberOfNights 1125}
7]
8[
9 {lastScrapedDate 2019-03-06}
10 {propertyName Makaha Valley Paradise with OceanView}
11 {propertyType Condominium}
12 {accommodatesNumber 4}
13 {maximumNumberOfNights 180}
14]
15[
16 {lastScrapedDate 2019-03-06}
17 {propertyName March 2019 availability! Oceanview on Sugar Beach!}
18 {propertyType Condominium}
19 {accommodatesNumber 4}
20 {maximumNumberOfNights 1125}
21]
22[
23 {lastScrapedDate 2019-03-06}
24 {propertyName Tropical Jungle Oasis}
25 {propertyType Condominium}
26 {accommodatesNumber 4}
27 {maximumNumberOfNights 1125}
28]
29[
30 {lastScrapedDate 2019-02-11}
31 {propertyName Hospede-se com acesso fácil.}
32 {propertyType Condominium}
33 {accommodatesNumber 4}
34 {maximumNumberOfNights 1125}
35]
go run date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-02-11}
3 {propertyName 2017 , férias no Rio}
4 {propertyType House}
5 {accommodatesNumber 2}
6 {maximumNumberOfNights 30}
7]
8[
9 {lastScrapedDate 2019-03-07}
10 {propertyName Newly renovated home}
11 {propertyType House}
12 {accommodatesNumber 2}
13 {maximumNumberOfNights 30}
14]
15[
16 {lastScrapedDate 2019-02-18}
17 {propertyName Vintage House For Rent}
18 {propertyType House}
19 {accommodatesNumber 2}
20 {maximumNumberOfNights 30}
21]
22[
23 {lastScrapedDate 2019-02-18}
24 {propertyName 4floor house in Taksim,Taksimde 4katli müstakil ev}
25 {propertyType House}
26 {accommodatesNumber 2}
27 {maximumNumberOfNights 30}
28]
29[
30 {lastScrapedDate 2019-02-16}
31 {propertyName 22 Oporto Guesthouse Cordoaria}
32 {propertyType House}
33 {accommodatesNumber 2}
34 {maximumNumberOfNights 30}
35]
go run date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-02-11}
3 {propertyName Horto flat with small garden}
4 {propertyType Apartment}
5 {accommodatesNumber 4}
6 {maximumNumberOfNights 1125}
7]
8[
9 {lastScrapedDate 2019-03-06}
10 {propertyName Private Room in Bushwick}
11 {propertyType Apartment}
12 {accommodatesNumber 1}
13 {maximumNumberOfNights 1125}
14]
15[
16 {lastScrapedDate 2019-02-11}
17 {propertyName Apt Linda Vista Lagoa - Rio}
18 {propertyType Apartment}
19 {accommodatesNumber 2}
20 {maximumNumberOfNights 1125}
21]
22[
23 {lastScrapedDate 2019-02-18}
24 {propertyName Charming Flat in Downtown Moda}
25 {propertyType House}
26 {accommodatesNumber 6}
27 {maximumNumberOfNights 1125}
28]
29[
30 {lastScrapedDate 2019-02-11}
31 {propertyName Catete's Colonial Big Hause Room B}
32 {propertyType House}
33 {accommodatesNumber 8}
34 {maximumNumberOfNights 1125}
35]
go run date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-03-06}
3 {propertyName Ocean View Waikiki Marina w/prkg}
4 {propertyType Condominium}
5 {accommodatesNumber 2}
6 {maximumNumberOfNights 365}
7]
8[
9 {lastScrapedDate 2019-03-07}
10 {propertyName New York City - Upper West Side Apt}
11 {propertyType Apartment}
12 {accommodatesNumber 2}
13 {maximumNumberOfNights 360}
14]
15[
16 {lastScrapedDate 2019-03-07}
17 {propertyName Sydney Hyde Park City Apartment (checkin from 6am)}
18 {propertyType Apartment}
19 {accommodatesNumber 2}
20 {maximumNumberOfNights 30}
21]
22[
23 {lastScrapedDate 2019-03-07}
24 {propertyName Private Room (2) in Guest House at Coogee Beach}
25 {propertyType House}
26 {accommodatesNumber 2}
27 {maximumNumberOfNights 365}
28]
29[
30 {lastScrapedDate 2019-03-06}
31 {propertyName ~Ao Lele~ Flying Cloud}
32 {propertyType Treehouse}
33 {accommodatesNumber 2}
34 {maximumNumberOfNights 30}
35]
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
3

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

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

Note

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

package com.mongodb.drivers;

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
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 com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("queryString",
19 new Document("defaultPath", "propertyType")
20 .append("query", "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019")));
21
22 // specify connection
23 String uri = "<connection-string>";
24
25 // establish connection and set namespace
26 try (MongoClient mongoClient = MongoClients.create(uri)) {
27 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
28 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
29 // run query and print results
30 collection.aggregate(Arrays.asList(agg,
31 limit(5),
32 project(fields(excludeId()) ))
33 ).forEach(doc -> System.out.println(doc.toJson()));
34 }
35 }
36}

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.

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
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 com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("queryString",
19 new Document("defaultPath", "propertyType")
20 .append("query", "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30")));
21
22 // specify connection
23 String uri = "<connection-string>";
24
25 // establish connection and set namespace
26 try (MongoClient mongoClient = MongoClients.create(uri)) {
27 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
28 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
29 // run query and print results
30 collection.aggregate(Arrays.asList(agg,
31 limit(5),
32 project(fields(excludeId()) ))
33 ).forEach(doc -> System.out.println(doc.toJson()));
34 }
35 }
36}

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.

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

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

Note

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

package com.mongodb.drivers;

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
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 com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("compound",
19 new Document("should", Arrays.asList(
20 new Document("autocomplete",
21 new Document("path", "lastScrapedDate")
22 .append("query", "2")),
23 new Document("autocomplete",
24 new Document("path", "maximumNumberOfNights")
25 .append("query", "1"))))));
26
27 // specify connection
28 String uri = "<connection-string>";
29
30 // establish connection and set namespace
31 try (MongoClient mongoClient = MongoClients.create(uri)) {
32 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
33 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
34 // run query and print results
35 collection.aggregate(Arrays.asList(
36 eq("$search", eq("compound", agg)),
37 limit(5),
38 project(fields(excludeId()) ))
39 ).forEach(doc -> System.out.println(doc.toJson()));
40 }
41 }
42}

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.

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
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 com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("compound",
19 new Document("should", Arrays.asList(
20 new Document("autocomplete",
21 new Document("path", "maximumNumberOfNights")
22 .append("query", "3")),
23 new Document("autocomplete",
24 new Document("path", "accommodatesNumber")
25 .append("query", "2"))))));
26
27 // specify connection
28 String uri = "<connection-string>";
29
30 // establish connection and set namespace
31 try (MongoClient mongoClient = MongoClients.create(uri)) {
32 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
33 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
34 // run query and print results
35 collection.aggregate(Arrays.asList(
36 eq("$search", eq("compound", agg)),
37 limit(5),
38 project(fields(excludeId()) ))
39 ).forEach(doc -> System.out.println(doc.toJson()));
40 }
41 }
42}

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
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Makaha Valley Paradise with OceanView",
11 "propertyType": "Condominium",
12 "accommodatesNumber": "4",
13 "maximumNumberOfNights": "180"
14}
15{
16 "lastScrapedDate": "2019-03-06",
17 "propertyName": "March 2019 availability! Oceanview on Sugar Beach!",
18 "propertyType": "Condominium",
19 "accommodatesNumber": "4",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-03-06",
24 "propertyName": "Tropical Jungle Oasis",
25 "propertyType": "Condominium",
26 "accommodatesNumber": "4",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Hospede-se com acesso fácil.",
32 "propertyType": "Condominium",
33 "accommodatesNumber": "4",
34 "maximumNumberOfNights": "1125"
35}
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "2017 , férias no Rio",
4 "propertyType": "House",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "30"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "Newly renovated home",
11 "propertyType": "House",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "30"
14}
15{
16 "lastScrapedDate": "2019-02-18",
17 "propertyName": "Vintage House For Rent",
18 "propertyType": "House",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "4floor house in Taksim,Taksimde 4katli müstakil ev",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "30"
28}
29{
30 "lastScrapedDate": "2019-02-16",
31 "propertyName": "22 Oporto Guesthouse Cordoaria",
32 "propertyType": "House",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "Horto flat with small garden",
4 "propertyType": "Apartment",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Private Room in Bushwick",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "1",
13 "maximumNumberOfNights": "1125"
14}
15{
16 "lastScrapedDate": "2019-02-11",
17 "propertyName": "Apt Linda Vista Lagoa - Rio",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "Charming Flat in Downtown Moda",
25 "propertyType": "House",
26 "accommodatesNumber": "6",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Catete's Colonial Big Hause Room B",
32 "propertyType": "House",
33 "accommodatesNumber": "8",
34 "maximumNumberOfNights": "1125"
35}
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "Ocean View Waikiki Marina w/prkg",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "365"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "New York City - Upper West Side Apt",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "360"
14}
15{
16 "lastScrapedDate": "2019-03-07",
17 "propertyName": "Sydney Hyde Park City Apartment (checkin from 6am)",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-03-07",
24 "propertyName": "Private Room (2) in Guest House at Coogee Beach",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "365"
28}
29{
30 "lastScrapedDate": "2019-03-06",
31 "propertyName": "~Ao Lele~ Flying Cloud",
32 "propertyType": "Treehouse",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
1
mongodb-driver-kotlin-coroutine
4.10.0 or higher version
2
3

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

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

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

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_airbnb")
13 val collection = database.getCollection<Document>("airbnb_mat_view")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("index", "date-number-fields-tutorial")
20 .append(
21 "queryString",
22 Document("defaultPath", "propertyType")
23 .append(
24 "query",
25 "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"
26 )
27 )
28 )
29
30 // run query and print results
31 val resultsFlow = collection.aggregate<Document>(
32 listOf(
33 agg,
34 limit(5),
35 project(fields(excludeId()))
36 )
37 )
38 resultsFlow.collect { println(it) }
39 }
40 mongoClient.close()
41}

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.

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.excludeId
4import com.mongodb.client.model.Projections.fields
5import com.mongodb.kotlin.client.coroutine.MongoClient
6import kotlinx.coroutines.runBlocking
7import org.bson.Document
8
9fun main() {
10 // establish connection and set namespace
11 val uri = "<connection-string>"
12 val mongoClient = MongoClient.create(uri)
13 val database = mongoClient.getDatabase("sample_airbnb")
14 val collection = database.getCollection<Document>("airbnb_mat_view")
15
16 runBlocking {
17 // define query
18 val agg = Document(
19 "\$search",
20 Document("index", "date-number-fields-tutorial")
21 .append(
22 "queryString",
23 Document("defaultPath", "propertyType")
24 .append(
25 "query",
26 "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
27 )
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(excludeId()))
37 )
38 )
39 resultsFlow.collect { println(it) }
40 }
41 mongoClient.close()
42}

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.

The code example performs the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

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

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

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_airbnb")
13 val collection = database.getCollection<Document>("airbnb_mat_view")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("index", "date-number-fields-tutorial")
20 .append(
21 "compound",
22 Document(
23 "should", listOf(
24 Document(
25 "autocomplete",
26 Document("path", "lastScrapedDate")
27 .append("query", "2")
28 ),
29 Document(
30 "autocomplete",
31 Document("path", "maximumNumberOfNights")
32 .append("query", "1")
33 )
34 )
35 )
36 )
37 )
38
39 // run query and print results
40 val resultsFlow = collection.aggregate<Document>(
41 listOf(
42 agg,
43 limit(5),
44 project(fields(excludeId()))
45 )
46 )
47 resultsFlow.collect { println(it) }
48 }
49 mongoClient.close()
50}

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.

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

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_airbnb")
13 val collection = database.getCollection<Document>("airbnb_mat_view")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("index", "date-number-fields-tutorial")
20 .append(
21 "compound",
22 Document(
23 "should", listOf(
24 Document(
25 "autocomplete",
26 Document("path", "maximumNumberOfNights")
27 .append("query", "3")
28 ),
29 Document(
30 "autocomplete",
31 Document("path", "accommodatesNumber")
32 .append("query", "2")
33 )
34 )
35 )
36 )
37 )
38
39 // run query and print results
40 val resultsFlow = collection.aggregate<Document>(
41 listOf(
42 agg,
43 limit(5),
44 project(fields(excludeId()))
45 )
46 )
47 resultsFlow.collect { println(it) }
48 }
49 mongoClient.close()
50}

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

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

Document{{lastScrapedDate=2019-03-06, propertyName=Tropical Jungle Oasis, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-03-06, propertyName=Honolulu 1 BR/1Bath Condo - Hilton Hawaiian, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=7}}
Document{{lastScrapedDate=2019-03-06, propertyName=Beautiful Apt, Tropical Resort, Steps to the Beach, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=45}}
Document{{lastScrapedDate=2019-03-06, propertyName=Ocean View in the heart of Waikiki, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-03-06, propertyName=Aloha, Kihei Bay Surf, New Pool and BBQ, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}}

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

Document{{lastScrapedDate=2019-03-11, propertyName=This room is perfect for responsible guests, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-06, propertyName=Queen Room at Beautiful Upscale Organic Farm, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-11, propertyName=Incredible space with amazing views, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-02-16, propertyName=Varanda Porto, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-06, propertyName=Bright, Clean, Quiet, Modern, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}

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

Document{{lastScrapedDate=2019-03-07, propertyName=Deluxe Loft Suite, propertyType=Apartment, accommodatesNumber=4, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-03-11, propertyName=3 chambres au coeur du Plateau, propertyType=Apartment, accommodatesNumber=6, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-02-16, propertyName=Be Happy in Porto, propertyType=Loft, accommodatesNumber=2, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-02-18, propertyName=Cozy house at Beyoğlu, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-02-16, propertyName=Downtown Oporto Inn (room cleaning), propertyType=Hostel, accommodatesNumber=2, maximumNumberOfNights=1125}}

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

Document{{lastScrapedDate=2019-03-06, propertyName=Ocean View Waikiki Marina w/prkg, propertyType=Condominium, accommodatesNumber=2, maximumNumberOfNights=365}}
Document{{lastScrapedDate=2019-03-07, propertyName=New York City - Upper West Side Apt, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=360}}
Document{{lastScrapedDate=2019-03-06, propertyName=~Ao Lele~ Flying Cloud, propertyType=Treehouse, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-06, propertyName=Banyan Bungalow, propertyType=Bungalow, accommodatesNumber=2, maximumNumberOfNights=300}}
Document{{lastScrapedDate=2019-03-06, propertyName=Luxury 1-Bdrm in Downtown Brooklyn, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=30}}
1
2

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

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.

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

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'queryString': {
9 'defaultPath': 'propertyType',
10 'query': 'propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019'
11 }
12 }
13 }, {
14 '$limit': 5
15 }, {
16 '$project': {
17 '_id': 0
18 }
19 }
20];
21
22MongoClient.connect(
23 "<connection-string>",
24 { useNewUrlParser: true, useUnifiedTopology: true },
25 async function (connectErr, client) {
26 assert.equal(null, connectErr);
27 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
28 let cursor = await coll.aggregate(agg);
29 await cursor.forEach((doc) => console.log(doc));
30 client.close();
31 }
32);

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.

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'queryString': {
9 'defaultPath': 'propertyType',
10 'query': 'propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30'
11 }
12 }
13 }, {
14 '$limit': 5
15 }, {
16 '$project': {
17 '_id': 0
18 }
19 }
20];
21
22MongoClient.connect(
23 "<connection-string>",
24 { useNewUrlParser: true, useUnifiedTopology: true },
25 async function (connectErr, client) {
26 assert.equal(null, connectErr);
27 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
28 let cursor = await coll.aggregate(agg);
29 await cursor.forEach((doc) => console.log(doc));
30 client.close();
31 }
32);

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.

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.

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

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'compound': {
9 'should': [
10 {
11 'autocomplete': {
12 'path': 'lastScrapedDate',
13 'query': '2'
14 }
15 }, {
16 'autocomplete': {
17 'path': 'maximumNumberOfNights',
18 'query': '1'
19 }
20 }
21 ]
22 }
23 }
24 }, {
25 '$limit': 5
26 }, {
27 '$project': {
28 '_id': 0
29 }
30 }
31];
32
33MongoClient.connect(
34 "<connection-string>",
35 { useNewUrlParser: true, useUnifiedTopology: true },
36 async function (connectErr, client) {
37 assert.equal(null, connectErr);
38 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
39 let cursor = await coll.aggregate(agg);
40 await cursor.forEach((doc) => console.log(doc));
41 client.close();
42 }
43);

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.

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'compound': {
9 'should': [
10 {
11 'autocomplete': {
12 'path': 'maximumNumberOfNights',
13 'query': '3'
14 }
15 }, {
16 'autocomplete': {
17 'path': 'accommodatesNumber',
18 'query': '2'
19 }
20 }
21 ]
22 }
23 }
24 }, {
25 '$limit': 5
26 }, {
27 '$project': {
28 '_id': 0
29 }
30 }
31];
32
33MongoClient.connect(
34 "<connection-string>",
35 { useNewUrlParser: true, useUnifiedTopology: true },
36 async function (connectErr, client) {
37 assert.equal(null, connectErr);
38 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
39 let cursor = await coll.aggregate(agg);
40 await cursor.forEach((doc) => console.log(doc));
41 client.close();
42 }
43);

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 date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-03-06',
3 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
4 propertyType: 'Condominium',
5 accommodatesNumber: '4',
6 maximumNumberOfNights: '1125'
7 }
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Makaha Valley Paradise with OceanView',
11 propertyType: 'Condominium',
12 accommodatesNumber: '4',
13 maximumNumberOfNights: '180'
14 }
15 {
16 lastScrapedDate: '2019-03-06',
17 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!',
18 propertyType: 'Condominium',
19 accommodatesNumber: '4',
20 maximumNumberOfNights: '1125'
21 }
22 {
23 lastScrapedDate: '2019-03-06',
24 propertyName: 'Tropical Jungle Oasis',
25 propertyType: 'Condominium',
26 accommodatesNumber: '4',
27 maximumNumberOfNights: '1125'
28 }
29 {
30 lastScrapedDate: '2019-02-11',
31 propertyName: 'Hospede-se com acesso fácil.',
32 propertyType: 'Condominium',
33 accommodatesNumber: '4',
34 maximumNumberOfNights: '1125'
35 }
36
node date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-02-11',
3 propertyName: '2017 , férias no Rio',
4 propertyType: 'House',
5 accommodatesNumber: '2',
6 maximumNumberOfNights: '30'
7 }
8 {
9 lastScrapedDate: '2019-03-07',
10 propertyName: 'Newly renovated home',
11 propertyType: 'House',
12 accommodatesNumber: '2',
13 maximumNumberOfNights: '30'
14 }
15 {
16 lastScrapedDate: '2019-02-18',
17 propertyName: 'Vintage House For Rent',
18 propertyType: 'House',
19 accommodatesNumber: '2',
20 maximumNumberOfNights: '30'
21 }
22 {
23 lastScrapedDate: '2019-02-18',
24 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev',
25 propertyType: 'House',
26 accommodatesNumber: '2',
27 maximumNumberOfNights: '30'
28 }
29 {
30 lastScrapedDate: '2019-02-16',
31 propertyName: '22 Oporto Guesthouse Cordoaria',
32 propertyType: 'House',
33 accommodatesNumber: '2',
34 maximumNumberOfNights: '30'
35 }
node date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-02-11',
3 propertyName: 'Horto flat with small garden',
4 propertyType: 'Apartment',
5 accommodatesNumber: '4',
6 maximumNumberOfNights: '1125'
7 }
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Private Room in Bushwick',
11 propertyType: 'Apartment',
12 accommodatesNumber: '1',
13 maximumNumberOfNights: '1125'
14 }
15 {
16 lastScrapedDate: '2019-02-11',
17 propertyName: 'Apt Linda Vista Lagoa - Rio',
18 propertyType: 'Apartment',
19 accommodatesNumber: '2',
20 maximumNumberOfNights: '1125'
21 }
22 {
23 lastScrapedDate: '2019-02-18',
24 propertyName: 'Charming Flat in Downtown Moda',
25 propertyType: 'House',
26 accommodatesNumber: '6',
27 maximumNumberOfNights: '1125'
28 }
29 {
30 lastScrapedDate: '2019-02-11',
31 propertyName: "Catete's Colonial Big Hause Room B",
32 propertyType: 'House',
33 accommodatesNumber: '8',
34 maximumNumberOfNights: '1125'
35 }
node date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-03-06',
3 propertyName: 'Ocean View Waikiki Marina w/prkg',
4 propertyType: 'Condominium',
5 accommodatesNumber: '2',
6 maximumNumberOfNights: '365'
7 }
8 {
9 lastScrapedDate: '2019-03-07',
10 propertyName: 'New York City - Upper West Side Apt',
11 propertyType: 'Apartment',
12 accommodatesNumber: '2',
13 maximumNumberOfNights: '360'
14 }
15 {
16 lastScrapedDate: '2019-03-07',
17 propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)',
18 propertyType: 'Apartment',
19 accommodatesNumber: '2',
20 maximumNumberOfNights: '30'
21 }
22 {
23 lastScrapedDate: '2019-03-07',
24 propertyName: 'Private Room (2) in Guest House at Coogee Beach',
25 propertyType: 'House',
26 accommodatesNumber: '2',
27 maximumNumberOfNights: '365'
28 }
29 {
30 lastScrapedDate: '2019-03-06',
31 propertyName: '~Ao Lele~ Flying Cloud',
32 propertyType: 'Treehouse',
33 accommodatesNumber: '2',
34 maximumNumberOfNights: '30'
35 }
1
2

If you created an index that uses dynamic mappings, you can query the airbnb_mat_view collection using the queryString operator. If you created an index that uses static mappings, you can query the airbnb_mat_view collection using the autocomplete operator.

The code example performs the following tasks:

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

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

The following query searches for properties where the property type is Apartment or Condominium, accommodates 2 people, and was listed in 2019.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'queryString': {
10 'defaultPath': 'propertyType',
11 'query': 'propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019'
12 }
13 }
14 }, {
15 '$limit': 5
16 }, {
17 '$project': {
18 '_id': 0
19 }
20 }
21])
22
23for i in result:
24 print(i)

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.

The following query searches for properties where the property type is House, accommodates 2 people, was listed in 2019, or allows stay for up to 30 nights.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'queryString': {
10 'defaultPath': 'propertyType',
11 'query': 'propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30'
12 }
13 }
14 }, {
15 '$limit': 5
16 }, {
17 '$project': {
18 '_id': 0
19 }
20 }
21])
22
23for i in result:
24 print(i)

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.

The code example performs the following tasks:

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

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

The following query searches for properties listed sometime starting with 2 and allows stay of number of nights starting with 1.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'compound': {
10 'should': [
11 {
12 'autocomplete': {
13 'path': 'lastScrapedDate',
14 'query': '2'
15 }
16 }, {
17 'autocomplete': {
18 'path': 'maximumNumberOfNights',
19 'query': '1'
20 }
21 }
22 ]
23 }
24 }
25 }, {
26 '$limit': 5
27 }, {
28 '$project': {
29 '_id': 0
30 }
31 }
32])
33
34for i in result:
35 print(i)

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.

The following query searches for properties that can allow stay of number of nights starting with 3 and accomodate number of people starting with 2.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'compound': {
10 'should': [
11 {
12 'autocomplete': {
13 'path': 'maximumNumberOfNights',
14 'query': '3'
15 }
16 }, {
17 'autocomplete': {
18 'path': 'accommodatesNumber',
19 'query': '2'
20 }
21 }
22 ]
23 }
24 }
25 }, {
26 '$limit': 5
27 }, {
28 '$project': {
29 '_id': 0
30 }
31 }
32])
33
34for i in result:
35 print(i)

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 date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-03-06',
3 'propertyName': 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
4 'propertyType': 'Condominium',
5 'accommodatesNumber': '4',
6 'maximumNumberOfNights': '1125'
7}
8{
9 'lastScrapedDate': '2019-03-06',
10 'propertyName': 'Makaha Valley Paradise with OceanView',
11 'propertyType': 'Condominium',
12 'accommodatesNumber': '4',
13 'maximumNumberOfNights': '180'
14}
15{
16 'lastScrapedDate': '2019-03-06',
17 'propertyName': 'March 2019 availability! Oceanview on Sugar Beach!',
18 'propertyType': 'Condominium',
19 'accommodatesNumber': '4',
20 'maximumNumberOfNights': '1125'
21}
22{
23 'lastScrapedDate': '2019-03-06',
24 'propertyName': 'Tropical Jungle Oasis',
25 'propertyType': 'Condominium',
26 'accommodatesNumber': '4',
27 'maximumNumberOfNights': '1125'
28}
29{
30 'lastScrapedDate': '2019-02-11',
31 'propertyName': 'Hospede-se com acesso fácil.',
32 'propertyType': 'Condominium',
33 'accommodatesNumber': '4',
34 'maximumNumberOfNights': '1125'
35}
python date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-02-11',
3 'propertyName': '2017 , férias no Rio',
4 'propertyType': 'House',
5 'accommodatesNumber': '2',
6 'maximumNumberOfNights': '30'
7}
8{
9 'lastScrapedDate': '2019-03-07',
10 'propertyName': 'Newly renovated home',
11 'propertyType': 'House',
12 'accommodatesNumber': '2',
13 'maximumNumberOfNights': '30'
14}
15{
16 'lastScrapedDate': '2019-02-18',
17 'propertyName': 'Vintage House For Rent',
18 'propertyType': 'House',
19 'accommodatesNumber': '2',
20 'maximumNumberOfNights': '30'
21}
22{
23 'lastScrapedDate': '2019-02-18',
24 'propertyName': '4floor house in Taksim,Taksimde 4katli müstakil ev',
25 'propertyType': 'House',
26 'accommodatesNumber': '2',
27 'maximumNumberOfNights': '30'
28}
29{
30 'lastScrapedDate': '2019-02-16',
31 'propertyName': '22 Oporto Guesthouse Cordoaria',
32 'propertyType': 'House',
33 'accommodatesNumber': '2',
34 'maximumNumberOfNights': '30'
35}
python date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-02-11',
3 'propertyName': 'Horto flat with small garden',
4 'propertyType': 'Apartment',
5 'accommodatesNumber': '4',
6 'maximumNumberOfNights': '1125'
7}
8{
9 'lastScrapedDate': '2019-03-06',
10 'propertyName': 'Private Room in Bushwick',
11 'propertyType': 'Apartment',
12 'accommodatesNumber': '1',
13 'maximumNumberOfNights': '1125'
14}
15{
16 'lastScrapedDate': '2019-02-11',
17 'propertyName': 'Apt Linda Vista Lagoa - Rio',
18 'propertyType': 'Apartment',
19 'accommodatesNumber': '2',
20 'maximumNumberOfNights': '1125'
21}
22{
23 'lastScrapedDate': '2019-02-18',
24 'propertyName': 'Charming Flat in Downtown Moda',
25 'propertyType': 'House',
26 'accommodatesNumber': '6',
27 'maximumNumberOfNights': '1125'
28}
29{
30 'lastScrapedDate': '2019-02-11',
31 'propertyName': "Catete's Colonial Big Hause Room B",
32 'propertyType': 'House',
33 'accommodatesNumber': '8',
34 'maximumNumberOfNights': '1125'
35}
python date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-03-06',
3 'propertyName': 'Ocean View Waikiki Marina w/prkg',
4 'propertyType': 'Condominium',
5 'accommodatesNumber': '2',
6 'maximumNumberOfNights': '365'
7}
8{
9 'lastScrapedDate': '2019-03-07',
10 'propertyName': 'New York City - Upper West Side Apt',
11 'propertyType': 'Apartment',
12 'accommodatesNumber': '2',
13 'maximumNumberOfNights': '360'
14}
15{
16 'lastScrapedDate': '2019-03-07',
17 'propertyName': 'Sydney Hyde Park City Apartment (checkin from 6am)',
18 'propertyType': 'Apartment',
19 'accommodatesNumber': '2',
20 'maximumNumberOfNights': '30'
21}
22{
23 'lastScrapedDate': '2019-03-07',
24 'propertyName': 'Private Room (2) in Guest House at Coogee Beach',
25 'propertyType': 'House',
26 'accommodatesNumber': '2',
27 'maximumNumberOfNights': '365'
28}
29{
30 'lastScrapedDate': '2019-03-06',
31 'propertyName': '~Ao Lele~ Flying Cloud',
32 'propertyType': 'Treehouse',
33 'accommodatesNumber': '2',
34 'maximumNumberOfNights': '30'
35}

Back

Date Range Filter

Next

How to Sort Your