gpt4 book ai didi

node.js - 迭代 mongoDB 集合,对每个项目执行异步聚合任务,完成后在 Response 中返回 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 23:21:38 25 4
gpt4 key购买 nike

尝试聚合 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 编程新手,并且遇到了这个小问题,非常感谢您的帮助。

最佳答案

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

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

关于node.js - 迭代 mongoDB 集合,对每个项目执行异步聚合任务,完成后在 Response 中返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com