Creating views in MongoDB

MongoDBDatabaseBig Data Analytics

To create views in MongoDB, use createView(). Let us create a collection with documents −

> db.demo113.insertOne(
... { _id: 1, StudentId: "101", "Details": { Name: "Chris", Age: 21 }, Subject: "MySQL" }
... );
{ "acknowledged" : true, "insertedId" : 1 }

Display all documents from a collection with the help of find() method −

> db.demo113.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "StudentId" : "101",
   "Details" : {
      "Name" : "Chris",
      "Age" : 21
   },
   "Subject" : "MySQL"
}

Following is the query to create views in MongoDB −

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

Display fields from a view with the help of find() method −

> db.firstView.find();

This will produce the following output −

{ "_id" : 1, "Subject" : "MySQL", "Name" : "Chris" }
raja
Published on 30-Mar-2020 12:03:18
Advertisements