javascript - Mongo - 基于名称的值总和聚合
问题描述
我正在尝试执行聚合函数以根据名称值计算成本和边际值的总和。因此,如果多个结果的名称为“Fake Provider”,我想要成本结果的总和和保证金结果的总和。
查询语句:
Pharmacy.aggregate([
{
$match: {
$and: [{ 'prescription.status': 'Ready for Pickup' }]
}
},
{
$project: {
'insurance.primary.name': 1,
'prescription.financial.cost': 1,
'prescription.financial.margin': 1
}
}
])
结果类似于:
[
{
"_id": "5cab98cd293bd54e94c40461",
"insurance": {
"primary": {
"name": "Fake Provider 1"
}
},
"prescription": [
{
"financial": {
"cost": "2.89",
"margin": "5.60"
}
},
{
"financial": {
"cost": "0.88",
"margin": "1.24"
}
}
]
},
{
"_id": "5cab98d0293bd54e94c40470",
"insurance": {
"primary": {
"name": "Fake Provider 1"
}
},
"prescription": [
{
"financial": {
"cost": "3.22",
"margin": "9.94"
}
},
{
"financial": {
"cost": "2.57",
"margin": "9.29"
}
},
{
"financial": {
"cost": "2.03",
"margin": "10.17"
}
}
]
}
]
我试图创建一个组声明,但没有任何运气。此外,成本和利润值当前存储为字符串。
$group: {
_id: '$insurance.primary.name',
Financial: {
$push: {
id: '$insurance.primary.name',
name: '$insurance.primary.name',
cost: '$prescription.financial.cost',
margin: '$prescription.financial.margin'
}
}
}
我想得到类似的结果:
[
{
"primaryInsurance": "Fake Provider 1",
"totalFinancialCost": "11.59",
"totalFinancialMargin": "36.24"
},
{
"primaryInsurance": "Fake Provider 2",
"totalFinancialCost": "12.82",
"totalFinancialMargin": "22.16"
}
]
我想我有一个解决方案,它使用查找和投影返回结果,然后使用 javascript 映射结果并执行加法。但是,我更愿意在数据库级别执行此操作。
解决方案
您必须首先展开“处方”字段,然后执行一组。试试这个管道:
let pipeline = [
{
$unwind: {
path: '$prescription'
}
},
{
$group: {
_id: '$insurance.primary.name',
totalFinancialCost: {
$sum: { $convert: { input: '$prescription.financial.cost', to: "decimal" } }
},
totalFinancialMargin: {
$sum: { $convert: { input: '$prescription.financial.margin', to: "decimal" } }
}
}
}]
请注意如何将值转换为十进制以执行求和。
推荐阅读
- arrays - 通过移动其他元素从 numpy 数组中删除子矩阵
- react-native - React 原生网页抓取提交表单
- ios - WKWebView 加载随机失败,NSURLErrorDomain 代码 -1200
- youtube-dl - 如何使用 youtube-dl 为下载的 youtube 视频刻录/硬编码字幕
- php - 使用 PHP、MYSql 和 Ajax 的分页无法正常工作
- c++ - 在地图中插入一对键
- mysql - 在 R 中实现 mysql rand() 函数的功能
- plugins - 当您为不同的操作系统创建应用程序快照时,snapcraft nodejs 插件如何处理 Node.js 环境?
- python - 线性回归模型预测功能不起作用
- security - 想知道可以绕过登录认证的网站的症状(目录遍历)