视图

    3.4 版本新功能

    本页索引

    从 3.4 开始, MongoDB 添加了基于已存在的集合或者 View (视图) 创建只读的 View 支持.

    创建视图

    创建或者定义一个视图, MongoDB 3.4 的介绍是:

    • the viewOn and pipelineoptions to the existingcreatecommand (anddb.createCollectionhelper):

      1. db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline> } )

      or if specifying a defaultcollationfor the view:

      1. db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline>, collation: <collation> } )
    • a newmongoshell helperdb.createView():

      1. db.createView(<view>, <source>, <pipeline>, <collation> )

      表现

    视图具备以下几种表现:

    只读

    视图是只读的; 通过视图进行写操作会报错.

    以下为支持视图的读操作:

    视图上的 find() 方法不支持如下projection 操作:

    你不能重命名视图.

    视图创建

    • 视图是在读操邹期间根据需要实时计算的, 同时 MongoDB 基于视图的读操作是底层聚合管道 (aggregation pipeline) 的一部分. 因此, 视图不支持一下操作:
    • 如果用于创建视图的聚合管道屏蔽了 _id 字段, 那么视图中的文档也会没有 _id 字段.

      分片视图

    如果视图依赖的集合是分片的, 那么视图也视为分片的. 因此, 你不能指定分片视图中 $lookupfrom字段与 $graphLookup 操作.

    Views 与 Collation

    • You can specify a default collation for a view at creation time. If no collation is specified, the view’s default collation is the “simple” binary comparison collator. That is, the view does not inherit the collection’s default collation.
    • 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.
    • If creating a view from another view, you cannot specify a collation that differs from the source view’s collation.
    • If performing an aggregation that involves multiple views, such as with $lookup or $graphLookup , the views must have the same collation.

      公共视图定义

    列出集合的操作, 如 db.getCollectionInfos()db.getCollectionNames(), 的结果中会包括它们的视图.

    IMPORTANT

    视图定义是公开的; 即在视图上的 db.getCollectionInfos()explain 操作将会包括定义视图的管道. 因此, 请避免直接引用视图定义中敏感的字段和值.

    删除视图

    要删除视图, 请使用视图上的 db.collection.drop() 方法.

    修改视图

    你可以通过删除或者重建的方式修改视图, 也可以使用 collMod 命令.

    支持操作

    以下操作支持视图, 除了本文中提到的限制除外:

    命令 方法
    create db.createCollection()
    db.createView()
    collMod
    db.getCollection()
    db.getCollectionInfos()
    db.getCollectionNames()
    find
    distinct
    count
    db.collection.aggregate()
    db.collection.find()
    db.collection.findOne()
    db.collection.count()
    db.collection.distinct()

    原文链接:https://docs.mongodb.com/v4.2/core/views/

    译者 :王恒