You can create a MongoDB Search index on a View to transform documents and collections. This enables you to partially index a collection, support incompatible data types or data models, and more.
The following examples use the sample_mflix and sample_airbnb sample databases.
Note
Disambiguation
This page discusses standard views. To learn about on-demand materialized views, see On-Demand Materialized Views.
To learn about the differences between the view types, see Comparison with On-Demand Materialized Views.
Requirements
You must use MongoDB 8.0 or higher.
On MongoDB v8.0+:
Use the Atlas UI or the Atlas Administration API to create MongoDB Search indexes on Views.
Run the MongoDB Search queries against the source collection. Reference the MongoDB Search index that was created on the View. These queries return the original documents as they appear in the source collection.
On MongoDB v8.1+, you can additionally:
Use
mongoshand Driver methods,db.collection.createSearchIndex(),db.collection.updateSearchIndex(),db.collection.dropSearchIndex(), and$listSearchIndexesto create and manage MongoDB Search indexes on Views.Run the MongoDB Search queries against the View.
To edit a View, you must have a User Admin role and use the collMod database command.
Limitations
MongoDB Search supports Views with the following stages:
Index names must be unique across a source collection and all of its Views.
MongoDB Search doesn't support view definitions with operators that produce dynamic results, such as the $$USER_ROLES system variable and the $rand aggregation operator.
MongoDB Search queries return the original documents as they appear in the source collection.
- To retrieve the transformed document, use the
storedSourceoption.
Permissions Required
To create a View, your role must have the createCollection privilege.
Examples
The following examples demonstrate how to create a View, partially index documents, and run queries against the index. The examples query the index by running the .aggregate command against the source collection or the View. MongoDB Search supports queries on View directly only on MongoDB v8.1 or later.
You can filter documents to partially index a collection. The following example creates a View on the sample_mflix.movies collection so that you can search for only movies released after January 1, 2000.
Connect to your cluster using mongosh.
To learn more, see Connect to a Cluster via mongosh.
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.
In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Data Explorer under the Database heading.
Expand the database and select the collection.
Click the Indexes tab for the collection.
Click the Search and Vector Search link in the banner.
The Search & Vector Search page displays.
Start your index configuration.
Make the following selections on the page and then click Next.
Search Type | Select the MongoDB Search index type. |
Index Name and Data Source | Specify the following information:
|
Configuration Method | For a guided experience, select Visual Editor. |
IMPORTANT: Your |fts| index is named ``autoembed_index` by default. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.
Check the status.
The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.
IMPORTANT: Larger collections take longer to index. You will receive an email notification when your index is finished building.
Query the releasedAfter2000Index partial index.
[ { "$search": { "index": "releasedAfter2000Index", "text": { "path": "title", "query": "foo" }, "sort": { "released": 1 } } } ]
SCORE: 3.120296001434326 _id: “573a13d2f29313caabd929f8” awards: Object cast: Array (4) countries: Array (1) directors: Array (1) fullplot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-win…" genres: Array (2) imdb: Object languages: Array (1) lastupdated: "2015-08-19 00:00:25.937000000" num_mflix_comments: 0 plot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-win…" poster: "https://m.media-amazon.com/images/M/MV5BMzE4OTczMTgxM15BMl5BanBnXkFtZT…" released: 2011-04-05T00:00:00.000+00:00 runtime: 150 title: "Foo Fighters: Back and Forth" tomatoes: Object type: "movie" year: 2011
Connect to your MongoDB Deployment using mongosh.
To learn more, see Connect to a Cluster via mongosh.
Query the releasedAfter2000Index partial index.
db.movies_ReleasedAfter2000.aggregate([ { $search: { index: "releasedAfter2000Index", text: { path: "title", query: "foo" }, sort: { released: 1 } } } ])
[ { _id: ObjectId('573a13d2f29313caabd929f8'), plot: "Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo ...", genres: [ 'Documentary', 'Music' ], runtime: 150, cast: [ 'Shawn Cloninger', 'William Goldsmith', 'Jessy Greene', 'Dave Grohl' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMzE4OTczMTgxM15BMl5BanBnXkFtZTcwNTU1NjQxOA@@._V1_SY1000_SX677_AL_.jpg', title: 'Foo Fighters: Back and Forth', fullplot: `Rising from the ashes of Nirvana, the Foo Fighters became a Grammy-winning sensation on their own. Sixteen years of the band's history comes to life in this documentary, from their demo tapes through the creation of their 2011 album, "Wasting Light."`, languages: [ 'English' ], released: ISODate('2011-04-05T00:00:00.000Z'), directors: [ 'James Moll' ], awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' }, lastupdated: '2015-08-19 00:00:25.937000000', year: 2011, imdb: { rating: 8.4, votes: 3745, id: 1853563 }, countries: [ 'USA' ], type: 'movie', tomatoes: { viewer: { rating: 4.4, numReviews: 857, meter: 96 }, dvd: ISODate('2011-08-08T00:00:00.000Z'), website: 'http://us.foofightersfilm.com/', production: 'Cinedigm Digital Cinema', lastUpdated: ISODate('2015-09-12T18:42:01.000Z') } } ]
The following example lets you search the sample_airbnb.listingsAndReviews collection for accomodatations based on a new totalPrice field, which is the sum of the price and cleaningFee fields. Also, since MongoDB Search doesn't support Decimal128 types, we transform the values to Double.
Connect to the cluster using mongosh.
To learn more, see Connect to a Cluster via mongosh.
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.
In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Data Explorer under the Database heading.
Expand the database and select the collection.
Click the Indexes tab for the collection.
Click the Search and Vector Search link in the banner.
The Search & Vector Search page displays.
Click Create Search Index to start your index configuration.
Make the following selections on the page and then click Next.
Search Type | Select the MongoDB Search index type. |
Index Name and Data Source | Specify the following information:
|
Configuration Method | Select JSON Editor to edit the raw index definition. |
Check the status.
The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.
IMPORTANT: Larger collections take longer to index. You will receive an email notification when your index is finished building.
Run a query on the totalPriceIndex index.
[ { "$search": { "index": "totalPriceIndex", "range": { "path": "totalPrice", "lte": 300 }, "returnStoredSource": true } } ]
SCORE: 1 _id: "10006546" totalPrice: 115 SCORE: 1 _id: "1001265" totalPrice: 215 SCORE: 1 _id: "10021707" totalPrice: 40 SCORE: 1 _id: "1003530" totalPrice: 270 SCORE: 1 _id: "10038496" totalPrice: 269 SCORE: 1 _id: "10051164" totalPrice: 250 SCORE: 1 _id: "10057447" totalPrice: 50 SCORE: 1 _id: "10057826" totalPrice: 205 SCORE: 1 _id: "10059244" totalPrice: 43 SCORE: 1 _id: "10066928" totalPrice: 140
Connect to your MongoDB deployment using mongosh.
To learn more, see Connect to a Cluster via mongosh.
Run a query on the totalPriceIndex index.
db.listingsAndReviews_totalPrice.aggregate([ { $search: { index: "totalPriceIndex", range: { path: "totalPrice", lte: 300 }, returnStoredSource: true } } ])
[ { _id: '10006546', totalPrice: 115 }, { _id: '1001265', totalPrice: 215 }, { _id: '10021707', totalPrice: 40 }, { _id: '1003530', totalPrice: 270 }, { _id: '10038496', totalPrice: 269 }, { _id: '10051164', totalPrice: 250 }, { _id: '10057447', totalPrice: 50 }, { _id: '10057826', totalPrice: 205 }, { _id: '10059244', totalPrice: 43 }, { _id: '10066928', totalPrice: 140 }, { _id: '10082422', totalPrice: 60 }, { _id: '10083468', totalPrice: 40 }, { _id: '10084023', totalPrice: 231 }, { _id: '10091713', totalPrice: 231 }, { _id: '10092679', totalPrice: 58 }, { _id: '10096773', totalPrice: 205 }, { _id: '10112159', totalPrice: 90 }, { _id: '10117617', totalPrice: 55 }, { _id: '10120414', totalPrice: 150 }, { _id: '10133554', totalPrice: 121 } ]
To index fields matching a naming pattern, use a View to transform your data so that the fields to index are nested in a sub-document. This enables you to use dynamic mappings for the sub-document path so that you can automatically search all new fields with the suffix _type, without any changes to your index definition.
The following View named listings_SearchableTypes only matches field names that end with _type in the sample_airbnb.listingsAndReviews collection. Specifically, the $set stage adds a new field named searchable_types, which contains the filtered fields with the term _type in the field name. The $arrayToObject contains the filter input (entire document) and condition (regex match for _type).
Connect to your cluster using mongosh.
To learn more, see Connect to a Cluster via mongosh.
Create a View named listings_SearchableTypes.
1 db.createView( 2 "listings_SearchableTypes", 3 "listingsAndReviews", 4 [ 5 { 6 "$set": { 7 "searchable_types": { 8 "$arrayToObject": { 9 "$filter": { 10 "input": { "$objectToArray": "$$ROOT" }, 11 "cond": { 12 "$regexMatch": { 13 "input": "$$this.k", 14 "regex": /_type$/ 15 } 16 } 17 } 18 } 19 } 20 } 21 } 22 ] 23 )
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.
In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Data Explorer under the Database heading.
Expand the database and select the collection.
Click the Indexes tab for the collection.
Click the Search and Vector Search link in the banner.
The Search & Vector Search page displays.
Click Create Search Index to start your index configuration.
Make the following selections on the page and then click Next.
Search Type | Select the MongoDB Search index type. |
Index Name and Data Source | Specify the following information:
|
Configuration Method | Select JSON Editor to edit the raw index definition. |
Edit the index definition.
Copy and paste the following index definition to replace the default index definition in the UI:
{ "analyzer": "lucene.standard", "searchAnalyzer": "lucene.standard", "mappings": { "dynamic": false, "fields": { "searchable_types": [ { "dynamic": { "typeSet": "tokenTypeSet" }, "type": "document" } ] } }, "typeSets": [ { "name": "tokenTypeSet", "types": [ { "type": "token" } ] } ] }
Check the status.
The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.
IMPORTANT: Larger collections take longer to index. You will receive an email notification when your index is finished building.
Query the View.
The following query searches the View named listings_SearchableTypes for house with a private room. To run this query, copy and paste the query, and click Search:
[ { "$search": { "index": "listingsSearchableTypes", "compound": { "should": [ { "text": { "path": "searchable_types.property_type", "query": "House" } }, { "text": { "path": "searchable_types.room_type", "query": "Private room" } } ] } } } ]
SCORE: 2.0530142784118652 _id: "10051164" name: "Catete's Colonial Big Hause Room B", searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1016739" name: 'Private Room (2) in Guest House at Coogee Beach', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "10324377" name: 'Suíte em local tranquilo e seguro', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1073607" name: 'Bright Inner West Terrace Value+', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1077686" name: 'BALAT', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "10990260" name: 'The Executive Posh Room', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "10992286" name: 'Holoholo Inn: Rain Forest (Priv-2)', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "11396243" name: 'Beautiful Ensuite Room -Easy access to city', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "1145567" name: 'ROOM + ENSUITE INNER CITY MOD HOUSE', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' SCORE: 2.0530142784118652 _id: "11464859" name: 'The Sassy Lilac Megan Love Room', searchable_types: Object property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed'
Connect to your MongoDB Deployment using mongosh.
To learn more, see Connect to a Cluster via mongosh.
Create a MongoDB Search index on the View.
The following index definition on the View named listingsSearchableTypes configures a typeSet to automatically index all fields in the searchable_types document as the string type. If you add new fields that match this pattern, MongoDB Search will automatically index those fields also.
db.listings_SearchableTypes.createSearchIndex( "listingsSearchableTypes", { "analyzer": "lucene.standard", "searchAnalyzer": "lucene.standard", "mappings": { "dynamic": false, "fields": { "searchable_types": [ { "type": "document", "dynamic": { "typeSet": "tokenTypeSet" } } ] } }, "typeSets": [ { "name": "tokenTypeSet", "types": [ { "type": "token" } ] } ] } )
Run a query on the totalPriceIndex index.
The following query searches the View named listings_SearchableTypes for house with a private room.
db.listings_SearchableTypes.aggregate([ { "$search": { "index": "listingsSearchableTypes", "compound": { "should": [ { "equals": { "path": "searchable_types.property_type", "value": "House" } }, { "equals": { "path": "searchable_types.room_type", "value": "Private room" } } ] } } }, { "$limit": 10 }, { "$project": { "_id": 0, "searchable_types": 1, "name": 1 } } ])
[ { name: "Catete's Colonial Big Hause Room B", searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Private Room (2) in Guest House at Coogee Beach', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Suíte em local tranquilo e seguro', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Bright Inner West Terrace Value+', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'BALAT', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'The Executive Posh Room', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Holoholo Inn: Rain Forest (Priv-2)', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'Beautiful Ensuite Room -Easy access to city', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'ROOM + ENSUITE INNER CITY MOD HOUSE', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } }, { name: 'The Sassy Lilac Megan Love Room', searchable_types: { property_type: 'House', room_type: 'Private room', bed_type: 'Real Bed' } } ]
To facet on unsupported field types such as boolean, objectId, or UUID, we recommend transforming the values to string type.
The following example creates a View on the sample_airbnb.listingsAndReviews namespace so that you can facet on the boolean type host.host_is_superhost field and the objectID type _id field.
Connect to your cluster using mongosh.
To learn more, see Connect to a Cluster via mongosh.
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.
In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Data Explorer under the Database heading.
Expand the database and select the collection.
Click the Indexes tab for the collection.
Click the Search and Vector Search link in the banner.
The Search & Vector Search page displays.
Click Create Search Index to start your index configuration.
Make the following selections on the page and then click Next.
Search Type | Select the MongoDB Search index type. |
Index Name and Data Source | Specify the following information:
|
Configuration Method | Select JSON Editor to edit the raw index definition. |
Edit the index definition.
Copy and paste the following index definition to replace the default index definition in the UI:
{ "mappings": { "dynamic": true, "fields": { "idString": { "type": "token" }, "superHostString": { "type": "token" } } } }
The preceding index definition indexes the idString and superHostString fields as the token type to support faceting on these fields.
Check the status.
The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.
IMPORTANT: Larger collections take longer to index. You will receive an email notification when your index is finished building.
Query the listingsAndReviews Source Collection.
The following query searches the summary field for ocean view in the listings_SearchableTypes index. The query retrieves the count of the number of properties that belong to each distinct _id and host.host_is_superhost. To run this query, copy and paste the query, and click Search:
[{ "$searchMeta": { "index": "listingsSearchableTypes", "facet":{ "operator": { "text": { "path": "summary", "query": "ocean view" } }, "facets": { "idFacet" : { "type" : "string", "path" : "idString", "numBuckets" : 10, }, "hostFacet": { "type" : "string", "path" : "superHostString" } } } } }]
count: Object lowerBound: 510 facet: Object idFacet: Object buckets: Array (10) 0: Object _id: "10082422" count: 1 1: Object _id: "10166986" count: 1 2: Object _id: "10266175" count: 1 3: Object _id: "10267144" count: 1 4: Object _id: "10317142" count: 1 5: Object _id: "10359729" count: 1 6: Object _id: "10392282" count: 1 7: Object _id: "10548991" count: 1 8: Object _id: "1067052" count: 1 9: Object _id: "1069531" count: 1 hostFacet: Object buckets: Array (2) 0: Object _id: "false" count: 370 1: Object _id: "true" count: 140
Connect to your MongoDB Deployment using mongosh.
To learn more, see Connect to a Cluster via mongosh.
Create a listings_SearchableTypes View.
The following View includes the following two fields:
idStringthat contains the value of the_idfield after converting it tostringtype.superHostStringthat contains the value of thehost.host_is_superhostfield after converting it tostringtype.
db.createView( "listings_SearchableTypes", "listingsAndReviews", [ { "$addFields": { "idString": { "$toString": "$_id" }, "superHostString": { "$toString": "$host.host_is_superhost" } } } ] )
Create a MongoDB Search index on the View.
The following index definition indexes the idString and superHostString fields as the token type to support faceting on these fields.
db.listings_SearchableTypes.createSearchIndex( "listingsSearchableTypes", { "mappings": { "dynamic": true, "fields": { "idString": { "type": "token" }, "superHostString": { "type": "token" } } } } )
Query the listingsSearchableTypes partial index.
The following query searches the listings_SearchableTypes index for ocean view in the summary field. The query retrieves the count of the number of properties that belong to each distinct _id and host.host_is_superhost.
db.listings_SearchableTypes.aggregate([{ "$searchMeta": { "index": "listingsSearchableTypes", "facet":{ "operator": { "text": { "path": "summary", "query": "ocean view" } }, "facets": { "idFacet" : { "type" : "string", "path" : "idString", "numBuckets" : 10, }, "hostFacet": { "type" : "string", "path" : "superHostString" } } } } }])
[ { count: { lowerBound: Long('510') }, facet: { idFacet: { buckets: [ { _id: '10082422', count: Long('1') }, { _id: '10166986', count: Long('1') }, { _id: '10266175', count: Long('1') }, { _id: '10267144', count: Long('1') }, { _id: '10317142', count: Long('1') }, { _id: '10359729', count: Long('1') }, { _id: '10392282', count: Long('1') }, { _id: '10548991', count: Long('1') }, { _id: '1067052', count: Long('1') }, { _id: '1069531', count: Long('1') } ] }, hostFacet: { buckets: [ { _id: 'false', count: Long('370') }, { _id: 'true', count: Long('140') } ] } } } ]
To search on Decimal128 type fields, we recommend converting the values to double type.
The following example creates a View on the sample_airbnb.listingsAndReviews namespace to add a field named totalPrice, which contains the sum of the price field and the cleaning_fee field after converting the values of these fields to double.
Connect to your cluster using mongosh.
To learn more, see Connect to a Cluster via mongosh.
Create a View named listings_SearchablePrice.
The following View includes a field named totalPrice that contains the sum of value of the price and cleaning-fee fields. Before adding the values of these fields, the following code converts the values of the price and cleaning-fee fields to double type.
1 db.createView( 2 "listings_SearchablePrice", 3 "listingsAndReviews", 4 [ 5 { 6 "$addFields": { 7 "totalPrice": { 8 "$add": [ 9 { 10 "$ifNull": [{ "$toDouble": "$price" }, 0] 11 }, 12 { 13 "$ifNull": [{ "$toDouble": "$cleaning_fee" }, 0] 14 } 15 ] 16 } 17 } 18 } 19 ] 20 )
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.
In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Data Explorer under the Database heading.
Expand the database and select the collection.
Click the Indexes tab for the collection.
Click the Search and Vector Search link in the banner.
The Search & Vector Search page displays.
Click Create Search Index to start your index configuration.
Make the following selections on the page and then click Next.
Search Type | Select the MongoDB Search index type. |
Index Name and Data Source | Specify the following information:
|
Configuration Method | Select JSON Editor to edit the raw index definition. |
Check the status.
The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.
IMPORTANT: Larger collections take longer to index. You will receive an email notification when your index is finished building.
Query the Source Collection.
The following query searches the index named listingsSearchablePrice for properties that cost between 100 and 200, both inclusive. To run this query, copy and paste the query, and click Search:
[ { "$search": { "index": "listingsSearchablePrice", "range": { "path": "totalPrice", "gte": 100, "lte": 200 } } } ]
SCORE: 1 _id: "10006546" access: "We are always available to help guests. The house is fully available t…" accommodates: 8 address: Object price: 80.00 SCORE: 1 _id: "10066928" access: "Le logement sera disponible en entier pour votre séjour." accommodates: 6 address: Object price: 140.00 SCORE: 1 _id: "10120414" access: "You can access to the rooftop where you have a beautiful view of Empir…" accommodates: 3 address: Object price: 150.00 SCORE: 1 _id: "10133554" access: "We have bathroom,wc,İnternet in rooms and under rooms we have cafe bar…" accommodates: 3 address: Object price: 121.00 SCORE: 1 _id: "10186755" access: "" accommodates: 2 address: Object price: 185.00 SCORE: 1 _id: "10213499" access: "Guests have access to backyard saltwater pool" accommodates: 2 address: Object price: 117.00 SCORE: 1 _id: "1022200" access: "" accommodates: 6 address: Object price: 135.00 SCORE: 1 _id: "10228731" access: "O quarto é privativo, com acesso a todas as acomodações do apartamento…" accommodates: 1 address: Object price: 149.00 SCORE: 1 _id: "10359729" access: "" accommodates: 4 address: Object price: 105.00 SCORE: 1 _id: "1036027" access: "" accommodates: 8 address: Object price: 100.00
Connect to your MongoDB Deployment using mongosh.
To learn more, see Connect to a Cluster via mongosh.
Create a listings_SearchablePrice View.
The following View includes a field named totalPrice that contains the sum of value of the price and cleaning-fee fields. Before adding the values of these fields, the following code converts the values of the price and cleaning-fee fields to double type.
db.createView( "listings_SearchablePrice", "listingsAndReviews", [ { "$addFields": { "totalPrice": { "$add": [ { "$ifNull": [{ "$toDouble": "$price" }, 0] }, { "$ifNull": [{ "$toDouble": "$cleaning_fee" }, 0] } ] } } } ] )
Query the listingsSearchablePrice index.
The following query searches the index named listingsSearchablePrice for properties that cost between 100 and 200, both inclusive.
db.listingsAndReviews.aggregate([ { "$search": { "index": "listingsSearchablePrice", "range": { "path": "totalPrice", "gte": 100, "lte": 200 } } }, { "$project": { "_id": 0, "totalPrice": 1, "price": 1, "cleaning_fee": 1 } } ])
[ { price: Decimal128('80.00'), cleaning_fee: Decimal128('35.00') }, { price: Decimal128('140.00') }, { price: Decimal128('150.00') }, { price: Decimal128('121.00') }, { price: Decimal128('185.00') }, { price: Decimal128('117.00'), cleaning_fee: Decimal128('0.00') }, { price: Decimal128('135.00') }, { price: Decimal128('149.00'), cleaning_fee: Decimal128('30.00') }, { price: Decimal128('105.00') }, { price: Decimal128('100.00') }, { price: Decimal128('138.00') }, { price: Decimal128('100.00'), cleaning_fee: Decimal128('80.00') }, { price: Decimal128('112.00'), cleaning_fee: Decimal128('0.00') }, { price: Decimal128('80.00'), cleaning_fee: Decimal128('30.00') }, { price: Decimal128('129.00'), cleaning_fee: Decimal128('60.00') }, { price: Decimal128('112.00') }, { price: Decimal128('100.00'), cleaning_fee: Decimal128('100.00') }, { price: Decimal128('85.00'), cleaning_fee: Decimal128('15.00') }, { price: Decimal128('85.00'), cleaning_fee: Decimal128('40.00') }, { price: Decimal128('135.00'), cleaning_fee: Decimal128('50.00') } ] Type "it" for more
Edit a View
The following example updates the movies_ReleasedAfter2000 MongoDB View for movies before 2000.
db.runCommand( { collMod: "movies_ReleasedAfter2000", viewOn: "movies", "pipeline": [ { $match: { $expr: { $lt: [ "$released", ISODate("2000-01-01T00") ] } } } ] } )
After you run this command, MongoDB Search automatically detects the change in the View definition and performs reindexing with no downtime.
Return the Pipelines for a View
The following example returns the pipelines on the movies_ReleasedAfter2000 View.
db.getCollectionInfos({ name: "movies_ReleasedAfter2000" })[0].options.pipeline
[ { '$match': { '$expr': { '$gt': [ '$released', ISODate('2000-01-01T00:00:00.000Z') ] } } } ]
Performance Considerations
Highly complex view transformations can increase indexing and query time. This is because the mongod must read the view definition when it filters and transforms the oplog entries during indexing (initial sync and steady state replication), and when it applies those transformations to the returned documents at query-time.
Consider creating a materialized view to avoid extra replication load on Atlas. You can also query the source collection directly to avoid query latency from the view transformation.
Troubleshoot
Indexes Change to FAILED
Indexes change to the FAILED status in the following scenarios:
You create an index on a View that is incompatible with MongoDB Search.
You edit a View in a way that does not meet the MongoDB Search compatibility requirements.
You remove or change a View's source collection.
For example, if one View is created on another View, and you change the parent View source to another collection.
Note
This limitation also applies if a View is a descendent of other Views. For example, you can't change or remove the source collection that all descendents originate from.
Indexes Change to STALE
Indexes change to the STALE status in the following scenarios:
Warning
If the aggregation pipeline defined in your View is incompatible with the documents in the collection, search replication fails. For example, if a $toDouble expression operates on a document field that contains an array, the replication fails. Ensure your View works with all documents in the collection without errors.
If the View definition causes an aggregation failure while an index is
READY, the index becomesSTALE. The index will return toREADYafter you resolve the document or change the view definition so that it doesn't fail anymore. WhenSTALE, the index remains queryable. If the index falls off the oplog, an index rebuild is triggered.If the View definition causes an aggregation pipeline failure while the index is
BUILDING, the index build is stuck until you fix the document. The index will return toREADYafter you resolve the document or change the view definition so that it doesn't fail anymore.
You can view index statuses in the Atlas UI on the index status details page.
Error: $search is only valid as the first stage in a pipeline
This error appears when you query a view using a MongoDB version before 8.1.
If you use a MongoDB version before 8.0, we recommend you upgrade to 8.1+ to query the view directly. You can upgrade to 8.0 to query the source collection.
If you use MongoDB 8.0, you must query the view index against the source collection. For example, run
.aggregate()on the collection instead of the view.
Index Process
When you create an MongoDB Search index on a View, the mongot process performs the same tasks as when you create an MongoDB Search index on a regular collection. The mongot process:
Creates MongoDB Search indexes based on the rules in the index definition for the collection.
Monitors change streams for the current state of the documents and indexes for the collections for which you defined the MongoDB Search indexes.
Processes MongoDB Search queries and returns the document IDs and other search metadata for the matching documents to
mongod, which then does a full document lookup and returns the results to the client.
When you create an MongoDB Search index on a View, the View definition is applied during Step 1 and 2, and the transformed documents are indexed based on the search index definition, then stored on disk.
Learn More
To learn more about Views, see Views.
To create a MongoDB Vector Search index on a View, see Use Views with MongoDB Vector Search.