Creating views in MongoDB

To create views in MongoDB, use the createView() method. Views are read-only virtual collections that display data from underlying collections based on aggregation pipelines.

Syntax

db.createView(
    "viewName",
    "sourceCollection",
    [aggregationPipeline]
)

Sample Data

Let us create a collection with sample documents ?

db.demo113.insertMany([
    { _id: 1, StudentId: "101", "Details": { Name: "Chris", Age: 21 }, Subject: "MySQL" },
    { _id: 2, StudentId: "102", "Details": { Name: "Alice", Age: 20 }, Subject: "MongoDB" },
    { _id: 3, StudentId: "103", "Details": { Name: "Bob", Age: 22 }, Subject: "Python" }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 1,
        "1": 2,
        "2": 3
    }
}

Display all documents from the collection ?

db.demo113.find().pretty();
{
    "_id": 1,
    "StudentId": "101",
    "Details": {
        "Name": "Chris",
        "Age": 21
    },
    "Subject": "MySQL"
}
{
    "_id": 2,
    "StudentId": "102",
    "Details": {
        "Name": "Alice",
        "Age": 20
    },
    "Subject": "MongoDB"
}
{
    "_id": 3,
    "StudentId": "103",
    "Details": {
        "Name": "Bob",
        "Age": 22
    },
    "Subject": "Python"
}

Creating a View

Create a view that projects only specific fields ?

db.createView(
    "firstView",
    "demo113",
    [ { $project: { "Name": "$Details.Name", Subject: 1 } } ]
);
{ "ok": 1 }

Querying the View

Display fields from the view using find() method ?

db.firstView.find();
{ "_id": 1, "Subject": "MySQL", "Name": "Chris" }
{ "_id": 2, "Subject": "MongoDB", "Name": "Alice" }
{ "_id": 3, "Subject": "Python", "Name": "Bob" }

Key Points

  • Views are read-only and cannot be directly modified
  • Views use aggregation pipelines to transform source collection data
  • Views are computed on-demand and don't store data physically

Conclusion

MongoDB views provide a convenient way to present transformed data from collections without storing duplicate information. They're perfect for creating simplified or filtered representations of complex data structures.

Updated on: 2026-03-15T01:56:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements