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
MongoDB vs MySQL
Both MongoDB and MySQL are popular database management systems (DBMS), but they are built for different purposes and have distinct features. MongoDB is a NoSQL database, designed for handling unstructured data with high scalability, while MySQL is a traditional relational database management system
6 min read
MongoDB Shell
MongoDB Shell is a powerful, interactive command-line interface that enables developers and database administrators to perform operations and manage their MongoDB databases using JavaScript syntax. Whether you're a beginner just starting with MongoDB or an experienced user, MongoDB Shell offers a co
5 min read
MongoDB - Regex
The $regex operator in MongoDB is a powerful tool that provides regular expression capabilities for pattern matching within strings in queries. It is particularly useful when the exact field value is unknown which allows for flexible and efficient searches within collections. In this article, We wil
6 min read
How MongoDB works ?
MongoDB is an open-source document-oriented database. It is used to store a larger amount of data and also allows you to work with that data. MongoDB is not based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data, that's
3 min read
BSON Types - MongoDB
BSON (Binary JSON) is the data storage format used by MongoDB to represent documents in a highly efficient and flexible manner. It extends JSON by supporting additional data types, optimizing storage, and improving query performance. Unlike standard JSON, BSON allows MongoDB to handle complex data s
3 min read
MongoDB Tutorial
In today's data-driven world, the ability to efficiently store and manage large amounts of data is crucial. MongoDB, a powerful NoSQL database, has become a go-to choice for developers looking for flexibility, scalability, and performance. Unlike traditional relational databases, MongoDB uses a docu
10 min read
When to Use MongoDB?
MongoDB is a powerful NoSQL database designed for managing unstructured and semi-structured data, offering high flexibility, scalability, and performance. Unlike relational databases such as MySQL, MongoDB employs a schema-less document-oriented data model, making it ideal for modern web application
6 min read
Mongoose Vs MongoDB
Mongoose is a powerful Object Data Modeling (ODM) library tailored for MongoDB and JavaScript, providing a structured approach to manage data in Node.js applications. By defining schemas that map to MongoDB documents, Mongoose ensures data integrity and simplifies CRUD operations. It offers features
6 min read
MongoDB - Index Types
In MongoDB, the power of efficient data retrieval lies in indexing. Indexes are crucial for optimizing query performance, making it faster to retrieve specific data from large collections without scanning every document. MongoDB, a NoSQL database, uses a binary tree data structure for indexing, ensu
9 min read
Mongoose Queries
Mongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an
7 min read