将对象数组中的int数组字段合并为mongodb聚合中的一个字符串字段
我想在将对象数组中的int数组字段值除以(10)后,将它们合并为一个字符串字段 现有文件格式如下:将对象数组中的int数组字段合并为mongodb聚合中的一个字符串字段,mongodb,type-conversion,aggregate,string-concatenation,Mongodb,Type Conversion,Aggregate,String Concatenation,我想在将对象数组中的int数组字段值除以(10)后,将它们合并为一个字符串字段 现有文件格式如下: { "no" : "2020921008981", "date" : ISODate("2020-04-01T05:19:02.263+0000"), "sale" : { "soldItems" : [ { "itemRefId" : "5b55ac7f0550de00210a3b24", "soldPrice" :
{
"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只支持数字类型,不支持字符串和双精度”
错误。如果您有任何想法,我们将不胜感激。请尝试以下聚合查询,其中的想法是:
- 首先将字段
除以10或使用soldPrice
- 使用和将其转换为字符串和concat
- 追加器
在每次reduce op之后追加,使用\n
- 使用创建新字段
db.collection.aggregate([
{
$addFields: {
"itemPriceList": {
$rtrim: {
input: {
$reduce: {
input: "$salesOrder.purchaseItems",
initialValue: "",
in: {
$concat: [
"$$value",
{
$toString: {
$divide: [
"$$this.soldPrice",
10
]
}
},
"\n"
]
}
}
},
chars: "\n"
}
}
}
}
]);
[
{
"_id": ObjectId("5a934e000102030405000000"),
"caseNumber": "2020921008981",
"itemPriceList": "80\n100",
"salesOrder": {
"purchaseItems": [
{
"itemRefId": "5b55ac7f0550de00210a3b24",
"soldPrice": 800
},
{
"itemRefId": "5b55ac7f0550de00210a3b25",
"soldPrice": 1000
}
]
},
"startTime": ISODate("2016-05-18T16:00:00Z")
}
]
结果:
db.collection.aggregate([
{
$addFields: {
"itemPriceList": {
$rtrim: {
input: {
$reduce: {
input: "$salesOrder.purchaseItems",
initialValue: "",
in: {
$concat: [
"$$value",
{
$toString: {
$divide: [
"$$this.soldPrice",
10
]
}
},
"\n"
]
}
}
},
chars: "\n"
}
}
}
}
]);
[
{
"_id": ObjectId("5a934e000102030405000000"),
"caseNumber": "2020921008981",
"itemPriceList": "80\n100",
"salesOrder": {
"purchaseItems": [
{
"itemRefId": "5b55ac7f0550de00210a3b24",
"soldPrice": 800
},
{
"itemRefId": "5b55ac7f0550de00210a3b25",
"soldPrice": 1000
}
]
},
"startTime": ISODate("2016-05-18T16:00:00Z")
}
]
db.case.aggregate([
{
$set:{
价格表:{
美元减少:{
输入:{
$map:{
输入:“$sale.soldItems.soldPrice”,
在:{$toString:{$divide:[“$$this”,10]}
}
},
初始值:“”,
在:{$concat:[“$$value”、“$$this”、“\n”]}
}
}
}
},
{
$项目:{
_id:0,
否:1,,
日期:1,
价目表:1
}
}
])
已根据要求发布了答案。看看这是否有效。也在您预期的o/p中。。。800/10是80而不是8.0,同样地,1000/10是100而不是10。你的意思是100度下潜吗?谢谢,伙计,这是你的初衷。我刚刚提出了一个与此相关的新场景的问题@我会尽快看一看的。您在哪个平台上构建应用程序?node/php/.net?只是好奇:——)