将MongoDB聚合操作中对象数组中的数组字段连接成一个字符串字段

4

我想将数组对象中的数组字段值连接成一个字符串字段。以下是现有文档格式:

{ 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"), 
  "notes" : [
    {
        "_id" : ObjectId("5b55aabe0550de0021097bf0"),  
        "term" : "BLA BLA"
    }, 
    {
        "_id" : ObjectId("5b55aabe0550de0021097bf1"), 
        "term" : "BLA BLA BLA"
    }, 
    {
        "_id" : ObjectId("5b55aabf0550de0021097ed2"), 
        "term" : "BLA"
     }
  ], 
   "client" : "John Doe"
}

所需文件格式:
{ 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"),  
  "notes" : "BLA BLA \n BLA BLA BLA \n BLA",
  "client" : "John Doe"
}

尝试使用 $project :
 { "$project": {    
      "notes": { 
            "$map": { 
                "input": "$notes", 
                "as": "u", 
                  "in": { 
                      "name": { "$concat" : [ "$$u.term", "\\n" ] } 
                  } 
             }
         }
     }
 }

但是这会返回这个:
{ 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000"),  
  "client" : "John Doe"
  "notes" : [
    {
        "name" : "BLA \n"
    }, 
    {
        "name" : "BLA BLA \n"
    }, 
    {
        "name" : "BLA BLA BLA \n"
    }
  ]
}

如何将其转换为所需格式?非常感谢您的任何想法!

编辑:

如果我们尝试将数组字段值相加,而不进行分组,该怎么做呢?

现有格式:

{
   "sale" : { 
       "bills" : [
        {
            "billNo" : "1234567890", 
            "billAmt" : NumberInt(1070), 
            "tax" : NumberInt(70) 
          }
       ]
    }, 
  "no" : "123456789",  
  "date" : ISODate("2020-04-01T05:19:02.263+0000")

}

Required :

{
 "no" : "123456789",  
 "date" : ISODate("2020-04-01T05:19:02.263+0000"),
 "total" : NumberInt(1140)
}
1个回答

4
您可以使用$reduce将字符串数组转换为单个字符串:
db.collection.aggregate([
    {
        $addFields: {
            notes: {
                $reduce: {
                    input: "$notes.term",
                    initialValue: "",
                    in: {
                        $cond: [ { "$eq": [ "$$value", "" ] }, "$$this", { $concat: [ "$$value", "\n", "$$this" ] } ]
                    }
                }
            }
        }
    }
])

Mongo Playground


已更新问题,附加了新场景,请查看。 - user8847697
@dineshalwis 请新开一个而不是编辑现有的。 - mickl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接