要在MongoDB中创建视图,请使用createView()。让我们创建一个包含文档的集合-
> db.demo113.insertOne( ... { _id: 1, StudentId: "101", "Details": { Name: "Chris", Age: 21 }, Subject: "MySQL" } ... ); { "acknowledged" : true, "insertedId" : 1 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo113.find().pretty();
这将产生以下输出-
{ "_id" : 1, "StudentId" : "101", "Details" : { "Name" : "Chris", "Age" : 21 }, "Subject" : "MySQL" }
以下是在MongoDB中创建视图的查询-
> db.createView( ... "firstView", ... "demo113", ... [ { $project: { "Name": "$Details.Name", Subject: 1 } } ] ... ) { "ok" : 1 }
借助find()方法从视图显示字段-
> db.firstView.find();
这将产生以下输出-
{ "_id" : 1, "Subject" : "MySQL", "Name" : "Chris" }