7

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?

bag531
  • 179
  • 1
  • 9
  • So you created a view via Node.js application, and you would like to access the view via the application ? – Wan B. Mar 16 '18 at 00:55

2 Answers2

10

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();
dcr24
  • 374
  • 1
  • 5
  • 11
1

I managed to do it as @dcr24 decribed. Here's the complete code

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
import DB_CONFIG from '../../server/constants/database'
/*
 * Requires the MongoDB Node.js Driver
 * https://mongodb.github.io/node-mongodb-native
 */

const agg = [
    {
        '$group': {
            '_id': '$entityGroupId',
            'totalVisits': {
                '$sum': '$visits'
            }
        }
    }, {
        '$sort': {
            'totalVisits': -1
        }
    }, {
        '$lookup': {
            'from': 'entities',
            'localField': '_id',
            'foreignField': 'entityGroupId',
            'as': 'entityGroup'
        }
    }
];

MongoClient.connect(
    DB_CONFIG.URL,
    {useNewUrlParser: true, useUnifiedTopology: true},
    async function (connectErr, client) {
        assert.equal(null, connectErr);
        const db = client.db('weally');
        // db.createView("entityGroupByVisits", 'complaintvisitcounts', agg)
        await db.createCollection('entityGroupByVisits', {
            viewOn: 'complaintvisitcounts',
            pipeline: agg,
        });
        client.close();
    });
Zied Hamdi
  • 2,400
  • 1
  • 25
  • 40