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.
On MongoDB v8.2+, you can additionally:
Use
$rankFusionin aggregation pipelines on Views.Query Views that include sharded sub-pipelines with
$lookupand$unionWith.
To edit a View, you must have a User Admin role and use the collMod database command.
Limitations
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
$randaggregation 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 show how to create a view, create a partial index, and run queries that use the index. The examples query the index by running the .aggregate command against the source collection or the view. MongoDB Search supports queries on views 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.
The following example lets you search the sample_airbnb.listingsAndReviews collection for accommodations 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, the values need to be transformed to Double.
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).
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.
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.
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.