View And Materialized View In MongoDB

MongoDB supports view and materialized view. This blog will give an overview of the views in MongoDB.

  1. DB View
    1. Create View
      1. db.createCollection() Syntax
      2. db.createView() Syntax
    2. Example
      1. Query the View
      2. Output
    3. Advantages
      1. Indexes
    4. Restrictions
    5. Supported Mongosh Methods
    6. Unsupported Operations
    7. Resource Locking
    8. Remove a View
  2. On-Demand Materialized Views
    1. On-Demand Materialized Views Creation
  3. Comparison Views And Materialized Views

DB View

MongoDB 3.4 views are non-materialised views, and behind the scenes, the engine runs an aggregation. Views in MongoDB are read-only, and they return a collection in much the same way as find() or aggregation() would.

MongoDB does not persist the view contents to disk. A view’s content is computed on-demand when a client queries the view.

Views use the indexes of the underlying collection. As a result, you cannot create, drop or re-build indexes on a standard view directly, nor get a list of indexes on the view.

Create View

Creating a view requires specifying a collection or a previous existing view. When a view is the source collection from another view, it allows us to execute a chained aggregation.

To create a view, we should use the db.createView() or db.createCollection() command, specifying the view name, the view source collection and the aggregation pipeline. This aggregation pipeline, as well as the other parameters, is saved in the system. Views collection. This is the only space that the view will use in the system. A new document is saved in the system. Views collection for each view created.

db.createCollection() Syntax


db.createCollection("<viewName>",
{
"viewOn" : "<source collection Name>",
"pipeline" : [<pipeline>],
"collation" : {<collation>}
})

db.createView() Syntax

db.createView("<viewName>","<source collection Name>",
[<pipeline>],
{
"collation" : {<collation>}
})

Example

Create a students collection to use for this example

db.students.insertMany( [
{ StudentID: 22001,year: 1,Branch: "CSE",score: 87 },
{ StudentID: 21001,year: 2,Branch: "ECE",score: 90 },
{ StudentID: 20010,year: 3,Branch: "CSE",score: 55 },
{ StudentID: 22021,year: 1,Branch: "CSE",score: 75 }
] )


Use db.createView() to create a view that is limited to first year students:

db.createView("firstYears",
"students",
[ { $match: { year: 1,Branch: 1 } } ]
)

or you can use db.createCollection() to Create a View

db.createCollection("firstYears",
{
viewOn: "students",
pipeline: [ { $match: { year: 1,Branch: 1 } } ]
})

Query the View

This example queries the view:

db.firstYears.find({year: 1})

Output

[
{ StudentID: 22001,year: 1,Branch: "CSE",score: 87 },
{ StudentID: 22021,year: 1,Branch: "CSE",score: 75 }
]

Advantages

Views are useful for many use cases. They bring benefits in terms of data privacy, performance tuning, code reuse, and analytics. Non-materialized views take up very little storage: view data is not stored, the only view definition is stored. Views add a layer of abstraction between the application and complex aggregation pipelines.

Indexes

views use the indexes of the underlying collection. As a result, you cannot create, drop or re-build indexes on a standard view directly, nor get a list of indexes on the view.

Restrictions

You must create views in the same database as the source collection.

  • A view definition pipeline cannot include the $out or the $merge stage. This restriction also applies to embedded pipelines, such as pipelines used in $lookup or $facet stages.
  • You cannot rename a view once it is created.

Supported Mongosh Methods

db.collection.aggregate()

db.collection.countDocuments()

db.collection.count()

db.collection.distinct()

db.collection.find()

db.collection.findOne()

db.createCollection()

db.createView()

db.getCollection()

db.getCollectionInfos()

db.getCollectionNames()

Unsupported Operations

Some operations are not available with views:

Resource Locking

db.createView() obtains an exclusive lock on the specified collection or view for the duration of the operation. All subsequent operations on the collection must wait until db.createView() releases the lock. db.createView() typically holds this lock for a short time.

Creating a view requires obtaining an additional exclusive lock on the system.views collection in the database. This lock blocks creation or modification of views in the database until the command completes.

Remove a View

To remove a view, use the db.collection.drop() method on the view.

For example, this command drops a view named first Years

db.firstYears.drop()

On-Demand Materialized Views

An on-demand materialised view is a pre-computed aggregation pipeline result that is stored on and read from disk. On-demand materialized views are typically the results of a $merge or $out stage.

You can create indexes directly on on-demand materialized views because they are stored on disk.

On-Demand Materialized Views Creation

Create a students collection to use for this example:

db.students.insertMany( [ 
{ StudentID: 22001,year: 1,Branch: "CSE",score: 87 }, 
{ StudentID: 21001,year: 2,Branch: "ECE",score: 90 }, 
{ StudentID: 20010,year: 3,Branch: "CSE",score: 55 }, 
{ StudentID: 22021,year: 1,Branch: "CSE",score: 75 } 
] )

On-Demand Materialized View: Initial Creation

You can use the $group and $merge stages to initially create a collection named Freshers (in the FirstYear database) from the data currently in the students collection.

db.getSiblingDB("college").students.aggregate( 
[
{ $group: { _id: { Student_year: "$year", dept: "$Branch" } } },
{ $merge : { into: { db: "FirstYear", coll: "Freshers" }, on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
] )

To view the documents in the new budgets collection:

db.getSiblingDB("FirstYear").Freshers.find().sort( { _id: 1 } )

Comparison Views And Materialized Views

ViewMaterialized View
A view is a virtual collection from one or more collections.
Which is never stored on the disk.
A materialized view is a physical copy of the base collection stored on the disk.
Views are updated every time when the base collection is updated.Updated manually or using triggers
Views are slow processing(If you update any content in the view, it is reflected in the original collection and would reflect in its view.
But this makes the performance of a view slower).
Fast Processing ( Materialized view responds faster in comparison to view. It is because the materialized view is precomputed).
No storage space needed.Stored in the disk
If the main collection is dropped then the view is not accessible.Even though the main collection is dropped the materialized view is accessible.
Views use the indexes of the underlying collection.On-demand materialized views will not use indexes of the underlying collection.you
Views Vs Materialized Views

We sincerely hope that this blog will help the readers to become more familiar with the view and materialized view. In the upcoming posts, let’s get more in-depth. Happy Learning!!!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s