我正在尝试执行MongoDB 3.6聚合,但找不到正确的方法。
问题出在下面。在执行了几个聚合步骤之后,我最终得到如下结果集:
[
{ _id: { month: 1, type: 'estimate' }, value: 50 },
{ _id: { month: 2, type: 'estimate' }, value: 40 },
{ _id: { month: 3, type: 'estimate' }, value: 35 },
{ _id: { month: 3, type: 'exact' }, value: 33.532 },
{ _id: { month: 4, type: 'estimate' }, value: 10 },
{ _id: { month: 4, type: 'exact' }, value: 11.244 },
]
它包含按月分组的值。每个月的价值可以“估计”或“精确”。现在,我想减少此结果以实现此目标:
[
{ _id: { month: 1 }, value: 50 },
{ _id: { month: 2 }, value: 40 },
{ _id: { month: 3 }, value: 33.532 },
{ _id: { month: 4 }, value: 11.244 },
]
基本上,我想尽可能使用类型为“精确”的值,并且仅在未知“精确”的月份内回退到“估计”值。
任何帮助或提示将不胜感激。我想在不在服务器上的数据库中执行该聚合。
答案 0 :(得分:2)
您可以简单地type
$sort,然后在下一个$first阶段使用$group,如果存在exact
,{{1} } 除此以外。试试:
estimate
打印:
db.col.aggregate([
{
$sort: { "_id.type": -1 }
},
{
$group:{
_id: "$_id.month",
value: { $first: "$value" }
}
},
{
$sort: { _id: 1 }
}
])
因此,按{ "_id" : 1, "value" : 50 }
{ "_id" : 2, "value" : 40 }
{ "_id" : 3, "value" : 33.532 }
{ "_id" : 4, "value" : 11.244 }
排序在此处被认为是优先事项,因为我们知道按词法type
将在exact
之前。您还可以更加明确,并添加名为estimate
(使用$cond进行了评估)的额外字段,然后按该权重进行排序:
weight