string-operators-tutorial

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: cloud, local, maven bom, gradle bom, maven, gradle, dynamic, static, and-query, or-query, yearquery, numericquery -->

How to Search Non-Alphabetical Data as Strings

This tutorial demonstrates how to run string-specific queries against non-string fields by converting the fields to strings and storing them in a [materialized view](https://www.mongodb.com/docs/manual/core/materialized-views.md#std-label-manual-materialized-views. The materialized view lets you use string-specific operators to query the converted fields and keep the original data intact in the source collection.

This tutorial takes you through the following steps:

  1. [Create a materialized view on a sample collection](https://www.mongodb.com/docs/search/tutorial/string-operators-tutorial.md#std-label-query-nonstring-create-mv

  2. [Create MongoDB Search indexes on the materialized view](https://www.mongodb.com/docs/search/tutorial/string-operators-tutorial.md#std-label-query-nonstring-create-index

  3. [Run MongoDB Search queries against the converted fields in the materialized view](https://www.mongodb.com/docs/search/tutorial/string-operators-tutorial.md#std-label-query-nonstring-run-queries

Before you begin, ensure that your cluster meets the requirements described in the [Prerequisites.](https://www.mongodb.com/docs/search/about/design-patterns.md#std-label-fts-design-patterns-prereqs

Create a Materialized View

This section demonstrates how to create a [materialized view](https://www.mongodb.com/docs/manual/core/materialized-views.md#std-label-manual-materialized-views named airbnb-mat-view on the [sample_airbnb.listingsAndReviews](https://www.mongodb.com/docs/manual/sample-data/sample-airbnb.md#std-label-sample-airbnb collection. This view stores various numeric and date fields from the source collection as string fields.

  1. In Atlas, go to the Clusters page for your project.

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

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

In the sidebar, click Clusters under the Database heading.

The Clusters page displays.

  1. Navigate to the collection.

For the cluster that contains the sample data, click Browse Collections.

In the left navigation pane, select the sample_airbnb database.

Select the listingsAndReviews collection.

  1. Click the Aggregation tab.

  2. Add the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage.

The [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage modifies data in the listingsAndReviews collection to convert existing fields into string type fields.

Click Add Stage.

Select [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project from the Select drop-down menu.

Add the following syntax to the aggregation pipeline editor. This does the following:

  • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

  • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

  • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

json { lastScrapedDate: { $dateToString: { format: "%Y-%m-%d", date: "$last_scraped" } }, accommodatesNumber: { $toString: "$accommodates" }, maximumNumberOfNights: { $toString: "$maximum_nights" }, propertyName: "$name", propertyType: "$property_type" }

  1. Add the $merge stage.

The [$merge](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

Click Add Stage.

Select the [$merge](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge stage from the Select drop-down menu.

Add the following syntax to the aggregation pipeline editor:

json { into: "airbnb_mat_view", whenMatched: "replace" }

  1. Click Merge Documents.

Refresh the list of collections to see the airbnb_mat_view collection.

To learn how to query the airbnb_mat_view collection in the Atlas UI, see [View, Filter, and Sort Documents.](https://www.mongodb.com/docs/atlas/atlas-ui/documents/#view--filter--and-sort-documents

1) Connect to your cluster in MongoDB Compass.

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass

2) Navigate to the sample_airbnb database.

On the Database screen, click the sample_airbnb database to access its collections.

3) Create a materialized view using the sales collection.

First, you'll run an aggregation pipeline on the listingsAndReviews collection to create the materialized view:

Click on the listingsAndReviews collection.

Click the Aggregations tab.

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.

  • Stage 1: [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    This pipeline stage transforms the data from the listingsAndReviews collection as follows:

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

    javascript { lastScrapedDate: { $dateToString: { format: "%Y-%m-%d", date: "$last_scraped" } }, accommodatesNumber: { $toString: "$accommodates" }, maximumNumberOfNights: { $toString: "$maximum_nights" }, propertyName: "$name", propertyType: "$property_type" }

  • Stage 2: [$merge](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    This pipeline stage writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

    javascript { into: "airbnb_mat_view", whenMatched: "replace" }

Click Run to execute the aggregation pipeline. This creates the initial airbnb_mat_view collection from the listingsAndReviews data.

4) Verify that the materialized view was created correctly.

Navigate back to the database view and click on the newly created airbnb_mat_view collection.

Click the Documents tab to view the documents in the collection.

  1. Connect to your cluster in MongoDB Compass.

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass

  1. Navigate to the sample_airbnb database.

On the Database screen, click the sample_airbnb database to access its collections.

  1. Create a materialized view using the sales collection.

First, you'll run an aggregation pipeline on the listingsAndReviews collection to create the materialized view:

Click on the listingsAndReviews collection.

Click the Aggregations tab.

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.

  • Stage 1: [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    This pipeline stage transforms the data from the listingsAndReviews collection as follows:

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

    javascript { lastScrapedDate: { $dateToString: { format: "%Y-%m-%d", date: "$last_scraped" } }, accommodatesNumber: { $toString: "$accommodates" }, maximumNumberOfNights: { $toString: "$maximum_nights" }, propertyName: "$name", propertyType: "$property_type" }

  • Stage 2: [$merge](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    This pipeline stage writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

    javascript { into: "airbnb_mat_view", whenMatched: "replace" }

Click Run to execute the aggregation pipeline. This creates the initial airbnb_mat_view collection from the listingsAndReviews data.

  1. Verify that the materialized view was created correctly.

Navigate back to the database view and click on the newly created airbnb_mat_view collection.

Click the Documents tab to view the documents in the collection.

1) Log in and connect to your cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.

Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

2) Verify and switch to the sample_airbnb database.

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

sh show dbs

Output:

sh 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

Run the following command to switch to the sample_airbnb database.

sh use sample_airbnb

Output:

sh switched to db sample_airbnb

3) Create a materialized view named airbnb_mat_view.

To create a materialized view, run the following query with the following aggregation pipeline stages:

  • [$project:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

  • [$merge:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    Writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

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

4) Verify that the materialized view was successfully created.

To verify, run the following command to view one document in the airbnb_mat_view materialized view:

```sh db.airbnb_mat_view.findOne()

```

Output:

json { _id: '10006546', lastScrapedDate: '2019-02-16', accommodatesNumber: '8', maximumNumberOfNights: '30', propertyName: 'Ribeira Charming Duplex', propertyType: 'House' }

  1. Log in and connect to your cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.

Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

  1. Verify and switch to the sample_airbnb database.

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

sh show dbs

Output:

sh 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

Run the following command to switch to the sample_airbnb database.

sh use sample_airbnb

Output:

sh switched to db sample_airbnb

  1. Create a materialized view named airbnb_mat_view.

To create a materialized view, run the following query with the following aggregation pipeline stages:

  • [$project:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

  • [$merge:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    Writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

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

  1. Verify that the materialized view was successfully created.

To verify, run the following command to view one document in the airbnb_mat_view materialized view:

```sh db.airbnb_mat_view.findOne()

```

Output:

json { _id: '10006546', lastScrapedDate: '2019-02-16', accommodatesNumber: '8', maximumNumberOfNights: '30', propertyName: 'Ribeira Charming Duplex', propertyType: 'House' }

1) Set up and initialize the .NET/C# project.

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

```shell # Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project dotnet new console

# Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver ```

For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.

2) Define the index.

Paste the following code into the Program.cs file.

This code uses the following aggregation pipeline stages to transform the data as described:

  • [$project:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

  • [$merge:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    Writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

```csharp using MongoDB.Bson; using MongoDB.Driver; using System;

public class CreateMaterializedView { // Replace the placeholder with your Atlas connection string private const string uri = ""; public static void Main(string[] args) { try { // Connect to your cluster var client = new MongoClient(uri); var database = client.GetDatabase("sample_airbnb"); var collection = database.GetCollection("listingsAndReviews");

           // Defines the aggregation pipeline
           var pipeline = new BsonDocument[]
           {
             new BsonDocument("$project", new BsonDocument
             {
               { "lastScrapedDate", new BsonDocument("$dateToString", new BsonDocument
                 {
                   { "format", "%Y-%m-%d" },
                   { "date", "$last_scraped" }
                 })
               },
               { "accommodatesNumber", new BsonDocument("$toString", "$accommodates") },
               { "maximumNumberOfNights", new BsonDocument("$toString", "$maximum_nights") },
               { "propertyName", "$name" },
               { "propertyType", "$property_type" }
             }),
             new BsonDocument("$merge", new BsonDocument
             {
               { "into", "airbnb_mat_view" },
               { "whenMatched", "replace" }
             })
           };

           // Executes the aggregation pipeline
           collection.Aggregate<BsonDocument>(pipeline);
           Console.WriteLine("Materialized view created!");
       }
       catch (Exception e)
       {
           Console.WriteLine($"Exception: {e.Message}");
       }
   }

}

```

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

Note:

For a local or self-managed deployment, your connection string should use the following format:

text mongodb://localhost:<port-number>/?directConnection=true

To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri

3) Create the index.

shell dotnet run Program.cs

Output:

text Materialized view created!

  1. Set up and initialize the .NET/C# project.

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

```shell # Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project dotnet new console

# Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver ```

For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.

  1. Define the index.

Paste the following code into the Program.cs file.

This code uses the following aggregation pipeline stages to transform the data as described:

  • [$project:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

  • [$merge:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    Writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

```csharp using MongoDB.Bson; using MongoDB.Driver; using System;

public class CreateMaterializedView { // Replace the placeholder with your Atlas connection string private const string uri = ""; public static void Main(string[] args) { try { // Connect to your cluster var client = new MongoClient(uri); var database = client.GetDatabase("sample_airbnb"); var collection = database.GetCollection("listingsAndReviews");

           // Defines the aggregation pipeline
           var pipeline = new BsonDocument[]
           {
             new BsonDocument("$project", new BsonDocument
             {
               { "lastScrapedDate", new BsonDocument("$dateToString", new BsonDocument
                 {
                   { "format", "%Y-%m-%d" },
                   { "date", "$last_scraped" }
                 })
               },
               { "accommodatesNumber", new BsonDocument("$toString", "$accommodates") },
               { "maximumNumberOfNights", new BsonDocument("$toString", "$maximum_nights") },
               { "propertyName", "$name" },
               { "propertyType", "$property_type" }
             }),
             new BsonDocument("$merge", new BsonDocument
             {
               { "into", "airbnb_mat_view" },
               { "whenMatched", "replace" }
             })
           };

           // Executes the aggregation pipeline
           collection.Aggregate<BsonDocument>(pipeline);
           Console.WriteLine("Materialized view created!");
       }
       catch (Exception e)
       {
           Console.WriteLine($"Exception: {e.Message}");
       }
   }

}

```

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

Note:

For a local or self-managed deployment, your connection string should use the following format:

text mongodb://localhost:<port-number>/?directConnection=true

To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri

  1. Create the index.

shell dotnet run Program.cs

Output:

text Materialized view created!

1) Set up and initialize the Go module.

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

```shell # Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project go mod init atlas-search-project

# Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo ```

For more detailed installation instructions, see the [MongoDB Go Driver documentation.](https://www.mongodb.com/docs/drivers/go/current/get-started.md#std-label-go-get-started

2) Define the index.

Create a create-materialized-view.go file in your project directory, and copy and paste the following code into the file.

This code uses the following aggregation pipeline stages to transform the data as described:

  • [$project:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

  • [$merge:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    Writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

```go package main

import ( "context" "fmt" "log"

"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"

)

func main() { // Create a context ctx := context.Background()

// Connect to MongoDB
uri := "<connection-string>"
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
    log.Fatal(err)
}

// Ensure the client will be properly disconnected when main exits
defer func() {
    if err := client.Disconnect(ctx); err != nil {
        log.Fatal(err)
    }
}()

// Ping the MongoDB server to verify the connection
if err := client.Ping(ctx, nil); err != nil {
    log.Fatal(err)
}

database := client.Database("sample_airbnb")
collection := database.Collection("listingsAndReviews")

// Create the aggregation pipeline
projectStage := bson.D{{Key: "$project", Value: bson.D{
    {Key: "lastScrapedDate", Value: bson.D{{Key: "$dateToString", Value: bson.D{
        {Key: "format", Value: "%Y-%m-%d"},
        {Key: "date", Value: "$last_scraped"},
    }}}},
    {Key: "accommodatesNumber", Value: bson.D{{Key: "$toString", Value: "$accommodates"}}},
    {Key: "maximumNumberOfNights", Value: bson.D{{Key: "$toString", Value: "$maximum_nights"}}},
    {Key: "propertyName", Value: "$name"},
    {Key: "propertyType", Value: "$property_type"},
}}}
mergeStage := bson.D{{Key: "$merge", Value: bson.D{
    {Key: "into", Value: "airbnb_mat_view"},
    {Key: "whenMatched", Value: "replace"},
}}}

pipeline := mongo.Pipeline{projectStage, mergeStage}

// Execute the aggregation
cursor, err := collection.Aggregate(ctx, pipeline)
if err != nil {
    log.Fatal(err)
}
defer cursor.Close(ctx)
fmt.Printf("Materialized view created!\n")

}

```

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

### Atlas Cluster

Your connection string should use the following format:

text mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

3) Create the index.

shell go run create-materialized-view.go

Output:

text Materialized view created!

  1. Set up and initialize the Go module.

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

```shell # Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project go mod init atlas-search-project

# Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo ```

For more detailed installation instructions, see the [MongoDB Go Driver documentation.](https://www.mongodb.com/docs/drivers/go/current/get-started.md#std-label-go-get-started

  1. Define the index.

Create a create-materialized-view.go file in your project directory, and copy and paste the following code into the file.

This code uses the following aggregation pipeline stages to transform the data as described:

  • [$project:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

  • [$merge:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    Writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

```go package main

import ( "context" "fmt" "log"

"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"

)

func main() { // Create a context ctx := context.Background()

// Connect to MongoDB
uri := "<connection-string>"
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
    log.Fatal(err)
}

// Ensure the client will be properly disconnected when main exits
defer func() {
    if err := client.Disconnect(ctx); err != nil {
        log.Fatal(err)
    }
}()

// Ping the MongoDB server to verify the connection
if err := client.Ping(ctx, nil); err != nil {
    log.Fatal(err)
}

database := client.Database("sample_airbnb")
collection := database.Collection("listingsAndReviews")

// Create the aggregation pipeline
projectStage := bson.D{{Key: "$project", Value: bson.D{
    {Key: "lastScrapedDate", Value: bson.D{{Key: "$dateToString", Value: bson.D{
        {Key: "format", Value: "%Y-%m-%d"},
        {Key: "date", Value: "$last_scraped"},
    }}}},
    {Key: "accommodatesNumber", Value: bson.D{{Key: "$toString", Value: "$accommodates"}}},
    {Key: "maximumNumberOfNights", Value: bson.D{{Key: "$toString", Value: "$maximum_nights"}}},
    {Key: "propertyName", Value: "$name"},
    {Key: "propertyType", Value: "$property_type"},
}}}
mergeStage := bson.D{{Key: "$merge", Value: bson.D{
    {Key: "into", Value: "airbnb_mat_view"},
    {Key: "whenMatched", Value: "replace"},
}}}

pipeline := mongo.Pipeline{projectStage, mergeStage}

// Execute the aggregation
cursor, err := collection.Aggregate(ctx, pipeline)
if err != nil {
    log.Fatal(err)
}
defer cursor.Close(ctx)
fmt.Printf("Materialized view created!\n")

}

```

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

### Atlas Cluster

Your connection string should use the following format:

text mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

  1. Create the index.

shell go run create-materialized-view.go

Output:

text Materialized view created!

1) Set up your Java project with the MongoDB Java driver.

In your IDE, create a new Maven or Gradle project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.

Select from the following Maven and Gradle tabs to view instructions for adding the BOM for each dependency manager:

### Maven

Add the following code to the dependencyManagement list in your pom.xml file:

xml <dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <version>5.5.1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>

To view a list of dependencies that the BOM manages, see the mongodb-driver-bom dependency listing on the Maven Repository website.

After adding the BOM, select from the following Maven and Gradle tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:

### Maven

Add the following code to the dependencies array in your Maven project's pom.xml file:

```xml org.mongodb mongodb-driver-sync 4.11.1

```

Run your package manager to install the dependencies to your project.

For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.

2) Define the index.

In your project's base package directory, create a CreateMaterializedView.java file and copy and paste the following code into this file.

This code uses the following aggregation pipeline stages to transform the data as described:

  • [$project:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project

    • Converts the date objects in the last_scraped field into string objects in the YYYY-MM-DD format using [$dateToString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateToString.md#mongodb-expression-exp.-dateToString and writes the output to a string field called lastScrapedDate.

    • Converts the number objects in the accommodates and minimum_nights fields into string values using [$toString](https://www.mongodb.com/docs/manual/reference/operator/aggregation/toString.md#mongodb-expression-exp.-toString and writes the output to number fields called accommodatesNumber and minimumNumberOfNights, respectively.

    • Includes the name and property_type string fields in the output and renames them to propertyName and propertyType respectively.

  • [$merge:](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge

    Writes the output fields from the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to a materialized view named airbnb_mat_view in the sample_airbnb database.

```java import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.AggregateIterable; import org.bson.Document;

import java.util.Arrays; import java.util.List;

public class CreateMaterializedView { public static void main(String[] args) { // Connect to MongoDB MongoClient client = MongoClients.create(""); MongoDatabase database = client.getDatabase("sample_airbnb"); MongoCollection collection = database.getCollection("listingsAndReviews");

       // Create the aggregation pipeline
       List<Document> pipeline = Arrays.asList(
           new Document("$project", new Document("lastScrapedDate", new Document("$dateToString", new Document("format", "%Y-%m-%d").append("date", "$last_scraped")))
                                    .append("accommodatesNumber", new Document("$toString", "$accommodates"))
                                    .append("maximumNumberOfNights", new Document("$toString", "$maximum_nights"))
                                    .append("propertyName", "$name")
                                    .append("propertyType", "$property_type")
                                    ),
           new Document("$merge", new Document("into", "airbnb_mat_view").append("whenMatched", "replace"))
       );

       // Execute the aggregation
       try {
         collection.aggregate(pipeline).toCollection();
       } catch (Exception e) {
           System.err.println("Error creating materialized view: " + e.getMessage());
       }
       System.out.println("Materialized view created!");
   }

}

```

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

Note:

For a local or self-managed deployment, your connection string should use the following format:

text mongodb://localhost:<port-number>/?directConnection=true

To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri

3) Compile and run the file to create the index.

Compile and run your application in your IDE or your shell.

shell javac CreateMaterializedView.java java CreateMaterializedView

Output:

text Materialized view created!

  1. Set up your Java project with the MongoDB Java driver.

In your IDE, create a new [Maven](https://maven.apache.o

(本文超出站点单文档体积上限,已截断)