【问题标题】:How to do Aggregation in Node js如何在 Node js 中进行聚合
【发布时间】:2021-02-25 16:58:54
【问题描述】:
我目前正在寻找在 Node js 中进行聚合的方法。我曾尝试过 $lts、$gte 等,但我想知道这些是否都归类为聚合。如果没有,请您给我一点启示。下面是我所拥有的。我可以举个例子说明如何聚合 $sum 或 $average。
$gte
db.contact.find("machine_unit" : {$gte:5}}, function(err,meibanlist){
if (err || !meibanlist ) console.log("Record is not found");
else meibanlist.forEach (function(machine_unit){
console.log(machine_unit);
});
});
【问题讨论】:
标签:
node.js
mongodb
mongodb-query
aggregation-framework
【解决方案1】:
以下示例演示了 node.js express 应用程序中的聚合操作,其中 REST API 端点从聚合中返回文档列表,该列表计算单个 $group 中的平均值和文档计数管道。
聚合操作使用 aggregate() 函数,该函数接受由数组表示的管道,将集合中的所有文档分组到 machine_Id 键上,并返回每个文档的总数组以及平均数量(即,如果文档有 amount 字段):
app.get('/meibanlist/machines', function (req, res) {
db.meibanlist.aggregate([
{
"$group": {
"_id": "$machine_Id",
"count": { "$sum": 1 },
"average": { "$avg": "$amount" }
}
}
], function (err, result) {
console.log(result);
res.json(result);
});
});