gpt4 book ai didi

javascript - 如何使用 node.js 在 mongodb 中获取按组名分组的聚合值?

转载 作者:行者123 更新时间:2023-11-30 19:00:45 24 4
gpt4 key购买 nike

我有一个用例,其中有 3 个集合。即每个模板的模板、组和 1-动态集合,将在创建模板后立即创建。

每个template 都包含devices,每个device 都包含一个groupId 组集合。动态采集存储模板设备推送的数据。

现在我需要找出组集合中按groupName分组的设备的聚合(总和)值。

以下是我收藏的示例数据。

模板数据

{
"_id": "5e0ae38729218b0a3861118b",
"templateId": "27127206822",
"devices": [
{
"deviceId": "waterTest",
"_id": "5e0ae49629218b0a3861118f",
"group": "5e0ae41d29218b0a3861118d",
},{
"deviceId": "Test",
"_id": "5e0af166981f39410cd89b72",
"group": "5e0af11d981f39410cd89b70"
}]
}

动态采集数据

[
{
"_id": "5e0ae793b1384737a4f855cf",
"template": "27127206822",
"deviceId": "waterTest",
"heat" : 20,
"humidity" : 10
},{
"_id": "5e0ae7a2b1384737a4f855d0",
"template": "27127206822",
"deviceId": "waterTest",
"heat" : 40,
"humidity" : 20
},{
"_id": "5e0ae890b1384737a4f855d3",
"template": "27127206822",
"deviceId": "waterTest",
"heat" : 60,
"humidity" : 50
},{
"_id": "5e0af188981f39410cd89b73",
"template": "27127206822",
"deviceId": "Test",
"heat": 60,
"humidity": 50
},{
"_id": "5e0af196981f39410cd89b74",
"template": "27127206822",
"deviceId": "Test",
"heat": 10,
"humidity": 20
}]

组数据

[{
"_id": "5e0af11d981f39410cd89b70",
"template": "5e0ae38729218b0a3861118b",
"groupName": "Flats"
},{
"_id": "5e0ae41d29218b0a3861118d",
"template": "5e0ae38729218b0a3861118b",
"groupName": "SPool"
}]

现在看看我到目前为止编写的聚合查询。

let templateId = "27127206822"; // Dynamic Collection

[err, templateData] = await to(mongoose.connection.db.collection(templateId)
.aggregate([
{
$lookup:{
from:"templates",
localField:"template",
foreignField:"templateId",
as:"template"
}
},{
$unwind:"$template"
},{
$unwind:"$template.devices"
},{
$lookup:{
from:"groups",
localField:"template.devices.group",
foreignField:"_id",
as:"group"
}
},{
$unwind:"$group"
},{
$group:{
_id: "$groupData.groupName",
heat:{$sum:"$heat"},
humidity:{$sum:"$humidity"},
count:{$sum:1}
}
}]));

现在,我需要获取按组集合的 groupName 分组的每个 deviceheat & humidity 总和。但是我得到了错误的数据。即,一个组的总和也被添加到所有其他组

**返回的输出**

//Am getting this Data
[
{
"_id": "Flats",
"heat": 190, // 2 group's data getting added in both the groups
"humidity": 150,
"count":5
},{
"_id": "SPool",
"heat": 190,
"humidity": 150,
"count":5
}]

预期输出

[
{
"_id": "Flats",
"heat": 70,
"humidity": 70,
"count":2
},{
"_id": "SPool",
"heat": 120,
"humidity": 80,
"count":3
}]

为了获得所需的结果,我是否遗漏了什么?

最佳答案

您可以添加 $group作为下一个聚合阶段并使用 $sum用于计数和加法:

{
$group: {
_id: "$group.groupName",
"count": { $sum: 1 },
"heat": { $sum: "$heat" },
"humidity": { $sum: "$humidity" }
}
}

关于javascript - 如何使用 node.js 在 mongodb 中获取按组名分组的聚合值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59533118/

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