迭代mongoDB集合,为每个项执行聚合的异步任务,并且当它们全部完成时返回响应中的JSON

问题描述 投票:1回答:2

尝试从MongoDB集合列表中聚合一些数据,并在对所有集合进行聚合时,我想返回所有合适集合的完整聚合,其中包含名称和聚合值作为JSON对象。 node.js编程新手,因此无法解决这个琐碎的问题。任何帮助赞赏

码:

app.get('/tester', (req, res) => {

    var AggArr = [];

    db.listCollections().toArray(function (err, collInfos) {
        async.forEachOf(collInfos, (value, key, callback) => {
            aggregate(value);
        }, err => {
            if (err)
                console.error(err.message);
            // configs is now a map of JSON data
            res.send(JSON.stringify(AggArr));
        });
    });
        function aggregate(collname) {
        if (collname.name.includes("_tps")) {
            db.collection(collname.name).aggregate([{
                        $match: {
                            $and: [{
                                    TIME: {
                                        $gte: new Date("2017-01-01T00:00:00Z")
                                    }
                                }, {
                                    TIME: {
                                        $lte: new Date("2017-12-31T23:59:59Z")
                                    }
                                }
                            ]
                        }
                    }, {
                        $group: {
                            _id: collname.name,
                            sum: {
                                $sum: "$TPS"

                            }
                        }
                    }
                ]).toArray(
                (err, result) => {
                if (err) {
                    return console.log(err)
                } else {
                    if (Object.keys(result).length === 0) {}
                    else {
                        console.log(result[0]);
                        AggArr.push(result[0]);
                    }
                }
            })
        }
        }
    })

我是Node.js编程的新手,并坚持这个微不足道的问题,任何帮助表示赞赏。

node.js mongodb mongodb-query aggregation-framework async.js
2个回答
1
投票

上述工作流程可以重构为以下内容

const pipeline = collectionName => (
    [
        { '$match': {
            'TIME': {
                '$gte': new Date("2017-01-01T00:00:00Z"), 
                '$lte': new Date("2017-12-31T23:59:59Z")
            }
        } }, 
        { '$group': {
            '_id': collectionName,
            'sum': { '$sum': "$TPS" }
        } }
    ]
);

db.listCollections().toArray((err, collInfos) => {
    const agg = collInfos
        .filter(col => col.name.includes("_tps"))
        .map(col => db.collection(col.name).aggregate(pipeline(col.name)).toArray());

    Promise.all(agg).then(data => {
        const results = data.map(d => d[0]);
        res.send(JSON.stringify(results));   
    });
});

1
投票

当您返回任何查询的响应时,它应如下所示。它将以JSON格式给出响应。

    app.get('/tester', (req, res) => {
    //DB Operaations
    if (success) {
        res.status(200).json(success);
    } else {
        res.status(500).json({
            message: 'Something went wrong'
        });
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.