View And Materialized View In MongoDB

Mydbops
Feb 9, 2023
10
Mins to Read
All

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

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("",
{
"viewOn" : "",
"pipeline" : [],
"collation" : {}
})
	

db.createView() Syntax

 
db.createView("","",
[],
{
"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

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!!!

No items found.

About the Author

Mydbops

Subscribe Now!

Subscribe here to get exclusive updates on upcoming webinars, meetups, and to receive instant updates on new database technologies.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.