【问题标题】:How can I concat an array of integer in MongoDB aggregation method?如何在 MongoDB 聚合方法中连接整数数组?
【发布时间】:2018-10-18 01:23:50
【问题描述】:

我在 mongodb 文档中有一个字段,它是一个整数数组,如下所示:

import_ids=[5200, 4710, 100]

我希望这个数组作为双##分隔字符串,所以预期的结果是

import_hashed="5200##4710##100"

我已经尝试在聚合方法的 $project 管道中使用以下代码。

 {
     $projct:{
      import_hashed:{
           $reduce:{
              input:"$import_ids",
              initialValue:"",
              in:{$concat:["$$value", "##", "$$this"]}
             }
         }
      } 
 }

但是没有找到结果,也没有错误!

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    你可以试试下面的聚合

    您可以使用$toLower 聚合将整数转换为字符串,如果您使用的是 mongodb,则可以使用$toString 4.0

    db.collection.aggregate([
      { "$project": {
        "import_hashed": {
          "$let": {
            "vars": {
              "key": {
                "$reduce": {
                  "input": "$import_ids",
                  "initialValue": "",
                  "in": { "$concat": ["$$value", "##", { "$toLower": "$$this" }] }
                }
              }
            },
            "in": { "$substrCP": ["$$key", 2, { "$strLenCP": "$$key" }] }
          }
        }
      }}
    ])
    

    输出

    { "import_hashed": "5200##4710##100 }
    

    【讨论】:

    • 感谢您对其工作的快速响应,但结果并不完美。我得到以下结果,它们是单个数组整数 import_hashed: "##287" 和来自多个数组元素 import_hashed: "##5200##4710##100" 我不希望结果字符串中出现第一个哈希。
    猜你喜欢
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多