Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorporating MongoDB views into Node

In MongoDB v3.4, views were added as a feature. However, I haven't been able to find any resources for how'd I'd use a view I created in a Node.js application. How would I go about doing this, specifically for an aggregation view?

like image 463
bag531 Avatar asked Mar 14 '18 14:03

bag531


People also ask

Can we connect MongoDB with Nodejs?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

Can we have views in MongoDB?

MongoDB provides two different view types: standard views and on-demand materialized views. Both view types return the results from an aggregation pipeline. Standard views are computed when you read the view, and are not stored to disk. On-demand materialized views are stored on and read from disk.


1 Answers

I also found this to be unclear. Confusingly, you need to use db.createCollection, unlike the createView command in the MongoDB shell. For example:

db.createCollection('myView', {
  viewOn: 'myCollection',
  pipeline: [],
});

Where pipeline is an Aggregation Pipeline. You can then access your View in the same way as a collection:

db.collection('myView').find();
like image 195
dcr24 Avatar answered Oct 04 '22 01:10

dcr24