In MongoDB, there are two primary types of views such as Standard Views and On-demand Materialized Views. These views offer different ways of managing data without directly modifying the underlying collections. While Standard Views are read-only and provide dynamic data access based on queries.
On-demand Materialized Views offer pre-computed, disk-stored data for faster retrieval. Both types have distinct characteristics in terms of storage, indexing, performance and maintenance. In this article, We will learn about the MongoDB Views in detail and so on.
MongoDB Views
- MongoDB Views is a powerful feature that allows us to create a virtual representation of our data by defining a query that retrieves and organizes documents from one or more collections.
- These views do not store data themselves instead of provide a way to access data dynamically based on the underlying queries.
Why are MongoDB Views Useful?
- View provides the specific data according to the aggregation pipeline.
- They are used to hide the important details of the documents and provide the necessary fields from the document.
- It is used to restrict access to certain fields from the document.
Connection Between Views and Data Aggregation
- Views in MongoDB are the virtual collection. Data aggregation is an important factor in creating a view. View represents the aggregated data from the collection.
- The aggregation pipeline is used to aggregate the data.$match, $group, $lookup and many more operations are used to aggregate data.
How to Create a View in MongoDB
Views in MongoDB can be created using db.createCollection() or db.createView( ). To create a view, a collection with documents is required.
For creating a View in MongoDB. Let have some data into our collection on which we will perform operations.
Query:
use GeeksforGeeks; // Database in use
db.createCollection('Teacher'); .//create Collection
// Insert document in a collection
db.Teacher.insertMany([
{ name: "Anil", Age: 28, Salary: 25000, year: 2 },
{ name: "Sunil", Age: 35, Salary: 35000, year: 5 },
{ name: "Ajay", Age: 35, Salary: 45000, year: 10 },
{ name: "Amit", Age: 45, Salary: 60000, year: 12 },
]);
Now we will use createView() method contains view name,source collection name and aggregation pipeline. The find() method is used to query the view in MongoDB.
Syntax:
db.createView( "view_name" ,"source_collection_name" ,pipeline )
Query:
Create views representing a teacher with more than 7 years of experience.
db.createView("ExperiencedTeacher", "Teacher", [
{ $match: { year: { $gt: 7 } } },
]);
// To query the view.
db.ExperiencedTeacher.find();
Output:
createView() in MongoDBExplanation: Teacher collection contains some documents with name, Age, Salary and year fields. View is created using createView() method. View contains documents with year field with value more than 7 year experience. Here find() method is used to query the view.
Create a View Using createCollection() in MongDB
View are created using createCollection() method. The method contains view name, source collection and the aggregation pipeline and find() method.
Syntax:
db.createCollection(" view_name", {
viewOn: "source_collection_name",
pipeline
});
Example: Create views to represent a teacher with more than 7 years of experience.
db.createCollection("ExperiencedTeacher", {
viewOn: "Teacher",
pipeline: [{ $match: { year: { $gt: 7 } } }],
});
// To query the view.
db.ExperiencedTeacher.find();
Output:
Create a View using createCollection() in MongDBExplanation: Teacher collection contains some documents with name,Age,Salary and year fields.View is created using createCollection() method .View contains documents with year field with value more than 7 year of experiences.
How to Open a View?
To "Open a view" implies to display the data within the view. The find() method is used to display the data within the view.
Syntax:
use database_name;
db.view_name.find();
Drop a View
View are read only, standard view are not stored in the database. As the task is complete view are dropped. drop() method is used to drop the view.
Syntax:
db.view_name.drop();
Example: db.ExperiencedTeacher.drop();
How to Create a Duplicate View?
Duplicate view contains the same documents as the original view. Duplicate view is created using createView() method.
Syntax:
db.createView( "Duplicate_view_name" ," Original_view_name" ,[] );
Example: Create a duplicate view on ExperiencedTeacher view.
db.createView("Experience","ExperiencedTeacher", [] ) ;
Output:
How to Duplicate ViewExplanation: Duplicate View is created using createView() method. The createView method contains duplicate view name,original view name and the aggregation pipeline is empty.
How to Modify a Views?
Method 1: Drop and Recreate the View
View cannot be modified directly using update() method. To modify the view it is dropped using drop() method and view is created again with new conditions.
Syntax:
db.view_name.drop();
db.createView( "view_name" ,"source_collection_name" ,pipeline_with_updated pipeline ,collation )
Example: Modify views to represent a teacher with less than 7 years of experience.
// Initial view
db.createView("ExperiencedTeacher", "Teacher", [
{ $match: { year: { $gt: 7 } } },
]);
// Drop and Recreate the View
db.ExperiencedTeacher.drop();
db.createView("ExperiencedTeacher", "Teacher", [
{ $match: { year: { $lt: 7 } } },
]);
Output:
Modify View in MongoDB- Method 1Explanation: Initially view is created which contains year field with value greater than 7. This view is dropped and new view is created using createView() method. This view contains year field with value less than 7.
Method 2: Using runCommand()
View are modified using the collMod command. The runCommand() method is used to carry out the modification in the view.
Syntax:
db.runCommand( collMod : "View_name " , viewOn: "source_collection ",pipeline )
Explanation:
- runCommand() is used to carry out operations that are not included with CRUD operations.
- collMod is used to modify validation rules.
- viewOn is used to define the aggregation pipeline that define the view.
Example: Modify views to represent a teacher with less than 7 years of experience.
db.runCommand({
collMod: "ExperiencedTeacher",
viewOn: "Teacher",
pipeline: [{ $match: { year: { $gt: 7 } } }],
});
Output:
Modify View in MongoDB Method 2Explanation: Initially view is created which contains year field with value greater than 7. This view is modified using collMod command. This view contains year field with value less than 7.
How to Use a View to Join Two Collections in MongoDB?
View are used to join two collections .createView() is used to join the two collections.
Syntax:
db.createView(
"joined_view_name", // View name
"collection1_name", // Source collection 1
[
{
// Pipeline for collection 1
$lookup: {
from: "collection2_name", // Source collection 2
localField: "field_in_collection1",
foreignField: "field_in_collection2",
as: "joined_data",
},
},
// Additional pipeline
]
);
Query:
Example: Join two collections using Views.
//First Collection
db.createCollection("users");
// Insert in first collection
db.users.insertMany([
{ name: "Anil", age: 25 },
{ name: "Jay", age: 30 },
{ name: "Om", age: 22 },
]);
//Second Collection
db.createCollection("orders");
// Insert in second Collection
db.orders.insertMany([
{ user_id: 1, product: "Pen", quantity: 2 },
{ user_id: 2, product: "Pencil", quantity: 1 },
{ user_id: 3, product: "Sneaker", quantity: 3 },
]);
//Create View to join two collections.
db.orders.insertMany([
{ user_id: 1, product: "Pen", quantity: 2 },
{ user_id: 2, product: "Pencil", quantity: 1 },
{ user_id: 3, product: "Sneaker", quantity: 3 },
]);
db.createView("userOrders", "users", [
{
$lookup: {
from: "orders",
localField: "_id",
foreignField: "user_id",
as: "orders",
},
},
{ $unwind: { path: "$orders",preserveNullAndEmptyArrays:true } },
{
$project: {
_id: 1,
name: 1,
orderId: "$orders._id",
product: "$orders.product",
quantity: "$orders.quantity",
},
},
]);
Output:
Use view to join two Collection in MongDB.Explanation: users and orders collections are joined using the view.
Standard Views vs On-demand Materialized Views in MongoDB
Standard Views | On-demand materialized views |
---|
They are read-only and are not stored on the disk | They are stored on a disk. |
They use the indexes of the original collection. | An index can be directly created. |
They require processing time to display views. | They are pre-computed hence offer fast retrieval |
They don't require maintenance | They require maintenance when there are updates in collection. |
Conclusion
Standard Views and On-demand Materialized Views each serve specific use cases in MongoDB. Standard Views provide a flexible, real-time method to access data dynamically but may require additional processing time. On the other hand, On-demand Materialized Views offer faster access to pre-computed data, but they require disk storage and periodic maintenance when the underlying collections are updated.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read