【发布时间】:2023-03-11 03:24:02
【问题描述】:
我的公司以字符串格式为某些键插入了数值。由于某些商业原因,它们无法转换为整数格式。
现在开始查询...
我正在编写一个 mongo 聚合查询,它为像联合利华这样的特定制造商跨商店计算 annual cost。看来我无法使用$toInt 方法将$cond 和$eq 块内的字符串转换为整数。
请在下面找到示例集。
[
{
_id: "ddfdfdfdggfgfgsg",
rate: "3323",
quantity_packs: "343",
shop_name: "Whole Foods",
manufacturer_name: "Unilever"
},
{
_id: "ddfdfdfsdsds",
rate: "434",
quantity_packs: "453",
shop_name: "Carrefour",
manufacturer_name: "Unilever"
},
{
_id: "dfdfdgcvgfgfvvv",
rate: "343",
quantity_packs: "23",
shop_name: "Target",
manufacturer_name: "Beirsdorf"
}
]
查询是
db.collection.aggregate([
{
$match: {
manufacturer_name: {
$in: [ "Unilever" ]
}
}
},
{
$group: {
_id: {
"Shop Name": "$shop_name"
},
"annual_cost": {
$sum: {
$cond: [
{
$eq: ["manufacturer_name", "Unilever"]
},
{ "$toInt": "$rate"},
0
]
}
},
"other_annual_cost": {
$sum: {
$cond: [
{
$ne: [$manufacturer_name, "Unilever"]
}, {"$toInt" : "$rate"},
0
]
}
},
"annual_qty": {
$sum: {
"$toInt": "$quantity_packs"
}
},
}
},
{
$project: {
"Purchase_Cost": {
$multiply: [ "$annual_cost", "$annual_qty" ]
},
"Other Manu Pur Cost": {
$multiply: ["$other_annual_cost", "$annual_qty"]
}
}
}
])
电流输出
[
{
_id: { 'Shop Name': 'Whole Foods' },
Purchase_Cost: 0
}
]
由于$rate 是字符串类型,因此乘法运算得到0,如here 所示。理想情况下,结果应该显示购买成本的某个整数值,如下所示。
预期输出
[
{
_id: { 'Shop Name': 'Whole Foods' },
Purchase_Cost: 234
}
]
任何建议都会有很大帮助。我想让这个查询以某种方式工作。
我已根据 Rajdeep 的回答更新了问题。
【问题讨论】:
-
@ArvindPal 我知道 $toInt 会进行类型转换。但是如何使用它以及在我的上下文中在哪里使用它?我想在 $cond 块中使用它之前将 $rate 转换为整数。
-
$toInt 工作正常,问题是你的“annual_cost”结果为 0,所以最后当你乘以它时,你也得到 0。您对“annual_cost”的期望值是多少?为什么你在条件上使用 sum?
标签: mongodb mongodb-query aggregation-framework