Introduction to MongoDB Views
When dealing with non-relational databases like MongoDB, creating views can be a valuable tool. A view in MongoDB is a virtual collection that presents data from one or more collections differently. They behave much like queries but are stored in the database for reuse. This guide will walk you through the steps of creating a view with a default collection in MongoDB, moving from the fundamentals to more advanced concepts.
Notes
Views are read-only and do not contain data themselves. Instead, they provide a different way to read data from underlying collections. They can abstract complexity, offer security by restricting access to underlying data, and simplify client interfaces by providing data in a specific shape or form.
Prerequisites
To create views in MongoDB, you need an existing MongoDB server, appropriate permissions to create views on the database, and basic knowledge of MongoDB query syntax.
Starting With The Basics
To create a view, use the db.createView()
method. The syntax is as follows:
db.createView(<viewName>, <source>, <pipeline>, <collation>)
Where:
viewName
is the name of the view.source
is the source collection.pipeline
is an array of aggregation pipeline stages that process documents.collation
is an optional argument specifying the collation.
Let’s create a simple view. Consider a collection employees
with documents like this:
{ _id: 1, name: "John Doe", department: "HR" }
{ _id: 2, name: "Jane Smith", department: "Engineering" }
To create a view that shows all documents from the employees
collection:
db.createView("employeesView", "employees", [])
This creates an empty operation; thus, the view called employeesView
will show all documents as they exist in the employees
collection.
Creating Views with Aggregation
You can create more complex views using aggregation pipelines. For example, suppose we only want to include the names and departments in our view and exclude the _id
fields. Here is how:
db.createView("employeesSummary", "employees", [
{ $project: { _id: 0, name: 1, department: 1 } }
])
The $project
stage in the pipeline specifies that the view should include the name
and department
fields and exclude the _id
field. The resulting view would show documents like this:
{ name: "John Doe", department: "HR" }
{ name: "Jane Smith", department: "Engineering" }
Working with Joins
In many cases, you might want to create a view that joins data from multiple collections. MongoDB’s aggregation framework supports this with the $lookup
stage. Say we have another collection, departments
, which looks like this:
{ _id: "HR", manager: "Alice" }
{ _id: "Engineering", manager: "Bob" }
To create a view that includes each employee’s name along with their department’s manager name:
db.createView("employeeManagers", "employees", [
{
$lookup: {
from: "departments",
localField: "department",
foreignField: "_id",
as: "departmentDetails"
}
},
{
$unwind: "$departmentDetails"
},
{
$project: { _id: 0, name: 1, manager: "$departmentDetails.manager" }
}
])
This view would produce documents like:
{ name: "John Doe", manager: "Alice" }
{ name: "Jane Smith", manager: "Bob" }
Advanced Techniques
Now let’s go through some advanced usage of MongoDB views.
Filtering Data in Views
You can also create views with filters. If our HR department wants a view of the HR employees:
db.createView("hrEmployees", "employees", [
{ $match: { department: "HR" } }
])
This view will only show documents of employees in the HR department.
Setting Collation for Views
Collation defines how MongoDB sorts and compares strings. You can set collation for views, which can be crucial for sorting data in languages other than English or if you need case-insensitive sorting. Here’s an example which sets a case-insensitive collation for a view:
db.createView("employeesViewCollated", "employees", [], { 'locale': 'en', 'strength': 2 })
The strength level 2 denotes case-insensitivity for the string comparison.
Managing Views
Once your view is created, you can manage it as a regular collection. However, certain operations are not applicable to views, as they are not physically stored. For example, you cannot drop an index on a view because views do not support indexes.
To view the list of views, you can simply show collections:
show collections
And to drop a view, you use the drop command:
db.getCollection('employeesView').drop()
Limitations of MongoDB Views
- Views do not support write operations; they are a read-only window into the data.
- Views cannot be sharded at this time.
- You cannot create an index on a view.
- There is a performance cost as MongoDB must execute the view’s aggregation pipeline to produce the result set.
Conclusion
In this guide, we covered how to create, use, and manage views in MongoDB, from the simplest use cases to more complex scenarios involving joins and filtering. Remember that while views are powerful, they also come with limitations, so it’s essential to keep these in mind when designing your database schema.