【发布时间】:2020-04-12 13:20:36
【问题描述】:
我想在将对象数组中的 int 数组字段值除以(除以 10)后将它们连接到一个字符串字段中。
这是现有的文档格式:
{
"no" : "2020921008981",
"date" : ISODate("2020-04-01T05:19:02.263+0000"),
"sale" : {
"soldItems" : [
{
"itemRefId" : "5b55ac7f0550de00210a3b24",
"soldPrice" : NumberInt(800),
},
{
"itemRefId" : "5b55ac7f0550de00210a3b25",
"soldPrice" : NumberInt(1000),
}
]
}
}
预期结果:
{
"no" : "2020921008981",
"date" : ISODate("2020-04-01T05:19:02.263+0000"),
"priceList" : "8.0 \n 10.0"
}
$reduce 的尝试:
priceList: {
$reduce: {
input: "$sale.soldItems.soldPrice",
initialValue: "",
in: {
$cond: [ { "$eq": [ { $toString: { $divide: [ "$$value", 10 ] } }, "" ] }, "$$this", { $concat: [ { $toString: { $divide: [ "$$value", 10 ] } }, "\n", "$$this" ] } ]
}
}
}
但最终得到"errmsg" : "$divide only supports numeric types, not string and double" 错误。任何想法将不胜感激。
【问题讨论】:
-
已根据要求发布了答案。看看这是否有效。同样在您的预期 o/p ... 800/10 是 80 而不是 8.0 并且类似地 1000/10 是 100 而不是 10。你的意思是潜水 100?
标签: mongodb type-conversion aggregate string-concatenation