node.js - 如何在 mongodb 中获取图形的条件平均数据?
问题描述
资料一:
{
"_id" : "5eb922b4c019811689c8f8e3",
"createdAt" : "2020-05-10T19:30:00.000Z",
"isManual" : false,
"value" : 0.66
}
数据2:
{
"_id" : "5eb922b4c019811689c8f8e3",
"createdAt" : "2020-05-10T19:30:00.000Z",
"isManual" : false,
"value" : 0.52
}
数据3:
{
"_id" : "5eb922b4c019811689c8f8e3",
"createdAt" : "2020-05-10T19:30:00.000Z",
"isManual" : true,
"value" : 0.34
}
现在我需要生成一个查询来获取值字段的平均值。考虑平均的isManual 键:
Response key expected:
total_fields = 3
manual_avg = 0.34 ((0.66 + 0.52)/3)
not_manual_avg = 0.13 ((0.34)/3)
解决方案
您可以尝试以下聚合查询:
db.collection.aggregate([
/** group all docs in collection */
{
$group: {
_id: null,
total_fields: { $sum: 1 }, /** count total no.of docs */
manual_avg: { $avg: { $cond: [ "$isManual", 0, "$value" ] } }, /** If 'isManual' is true pass-in 0 else actual value to average */
not_manual_avg: { $avg: { $cond: [ "$isManual", "$value", 0 ] } }
}
},
/** Optional stage */
{
$project: { _id: 0,total_fields: 1, manual_avg: { $trunc: [ "$manual_avg", 2 ] }, not_manual_avg: { $trunc: [ "$not_manual_avg", 2 ] }
}
}
])
测试: mongoplayground
推荐阅读
- angular - 使用茉莉弹珠进行单元测试
- python - 如果我的 Mac 中有 3.x python 版本,为什么 PythonTeX 正在运行 2.x 版本?
- mysql - 将 SQL Query 中两列之间的百分比计算为每天另一列
- gstreamer - GStreamer。从 udp 播放原始 h264
- c++ - 流式传输到多个输出设备
- amazon-web-services - ECS 移除所有实例
- solr - 如何在 Hybris 的前端显示 facet 值?
- python - Django Python 组按 IP 网络掩码
- spring-boot - 服务中的多对多关系使用
- c# - 如何选择元素的后代字符串?