将MongoDB视图合并到Node中



在MongoDB v3.4中,视图被添加为一项功能。但是,我无法找到有关如何使用我在 Node.js 应用程序中创建的视图的任何资源。我将如何执行此操作,特别是对于聚合视图?

我也

发现这不清楚。令人困惑的是,你需要使用 db.createCollection,这与 MongoDB shell 中的 createView 命令不同。例如:

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

其中pipeline是聚合管道。然后,您可以通过与访问集合相同的方式访问视图:

db.collection('myView').find();

我设法按照@dcr24描述的那样做到了。这是完整的代码

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();
    });

最新更新