Views¶
3.4 新版功能.
On this page
Starting in version 3.4, MongoDB adds support for creating read-only views from existing collections or other views.
Create View¶
To create or define a view, MongoDB 3.4 introduces:
the viewOn and pipeline options to the existing create command (and db.createCollection helper):
db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline> } )
or if specifying a default collation for the view:
db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline>, collation: <collation> } )
a new mongo shell helper db.createView():
db.createView(<view>, <source>, <pipeline>, <collation> )
Behavior¶
Views exhibit the following behavior:
- Views are read-only; write operations on views will error.
- Views use indexes of the underlying collection.
- Views are considered sharded if their underlying collection is sharded. As such, you cannot specify a sharded view for the from field in $lookup and $graphLookup operations.
- Views are computed on demand during read operations, and MongoDB
executes read operations on views as part of the underlying
aggregation pipeline. As such, views do not support operations
such as:
- db.collection.mapReduce(),
- $text operator, since $text operation in aggregation is valid only for the first stage,
- geoNear command and $geoNear pipeline stage.
- find() operations on views do not support the following projection operators:
- If the aggregation pipeline used to create the view suppresses the _id field, documents in the view do not have the _id field.
- You cannot rename views.
- String comparisons on the view use the view’s default collation. An operation that attempts to change or override a view’s default collation will fail with an error.
Operations that lists collections, such as db.getCollectionInfos() and db.getCollectionNames(), include views in their outputs.
重要
The view definition is public; i.e. db.getCollectionInfos() and explain operations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.
Drop a View¶
To remove a view, use the db.collection.drop() method on the view.