我有两个芒果聚合管道输出结果。现在,我希望将这两个管道组合起来,以获得一个单独的输出。
请找下面的样品收集。
[
{
_id: "ddfdfdfdggfgfgsg",
rate: "3323",
quantity_packs: "343",
shop_name: "Whole Foods",
sku: "20"
manufacturer_name: "Unilever"
},
{
_id: "ddfdfdfsdsds",
rate: "434",
quantity_packs: "453",
shop_name: "Carrefour",
sku: "200"
manufacturer_name: "Unilever"
},
{
_id: "dfdfdgcvgfgfvvv",
rate: "343",
quantity_packs: "23",
shop_name: "Target",
manufacturer_name: "Beirsdorf"
sku: "34"
}
]
请在下面找到我的问题。
优先查询
db.collection.aggregate([
{
$match: {
manufacturer_name: {
$in: [ "unilever" ]
}
}
},
{
$group: {
_id: {
"Shop Name": "$shop_name"
},
"total_sku": {
"$addToSet": "$sku"
},
"annual_cost": {
$sum: {
$cond: [
{
$eq: ["$manufacturer_name", "unilever"]
},
{
"$toDouble": "$rate"
},
0
]
}
},
"annual_qty": {
$sum: {
"$toDouble": "$annual_qty"
}
}
}
},
{
$project: {
"sku count": {
"$size": "$total_sku"
},
"Annual Cost WO GST": {
$multiply: [ "$annual_cost", "$annual_qty" ]
},
}
},
])
第一次查询的结果
[
{
_id: { 'Hospital Name': '7AM mart' },
'sku count': 29,
'Annual Cost WO GST': 79968887.67999999
},
{
_id: { 'Shop Name': 'Apex' },
'sku count': 20,
'Annual Cost WO GST': 1779192666.96
}
]
第二次查询
db.collection.aggregate([
{
$match: {
$expr: {
$ne: ["$manufacturer_name", "unilever"]
}
}
},
{
$group: {
_id: {
"Shop Name": "$shop_name"
},
"annual_cost_wo_gst_wo_manu": {
$sum: {
"$toDouble": "$rate"
}
},
"annual_qty": {
$sum: {
"$toDouble": "$annual_qty"
}
}
}
},
{
$project: {
"Ann Cost For Other Manufacturers": {
$multiply: ["$annual_cost_wo_gst_wo_manu", "$annual_qty"]
},
}
}
])
第二次查询的结果
[
{
_id: { 'Hospital Name': 'Apex' },
'Ann Cost For Other Manufacturers': 25246715130525.273
},
{
_id: { 'Hospital Name': '7AM Mart' },
'Ann Cost For Other Manufacturers': 1347701834351.495
}
]
如前所述,我想以某种方式将的结果与正确地映射项目结合起来。
预期结果
[
{
_id: { 'Hospital Name': '7AM mart' },
'sku count': 29,
'Annual Cost WO GST': 79968887.67999999
'Ann Cost For Other Manufacturers': 1347701834351.495
},
{
_id: { 'Shop Name': 'Apex' },
'sku count': 20,
'Annual Cost WO GST': 1779192666.96
'Ann Cost For Other Manufacturers': 25246715130525.273
}
]
发布于 2021-07-21 13:53:39
您的2个查询不完全生成所述的输出。不过,您可以首先执行不相关的$lookup
来执行第二个查询,将辅助查询的结果存储在字段/对象中。然后您可以继续您的第一个查询。最后,从先前存储的字段/对象中提取辅助查询的结果。
下面是一个蒙戈游乐场,它对原始示例进行了一些修改,供您参考。
https://stackoverflow.com/questions/68470421
复制相似问题