繁体   English   中英

MongoDB 聚合:管道中的串联字符串

[英]MongoDB aggregation: concatenation strings in pipeline

我是 MongoDB 的新手,遇到了一个问题。 在我的聚合管道中,我有这样的数据结构:

[
  {
    "_id": 1,
    "letter": "b"
  },
  {
    "_id": 2,
    "letter": "b"
  },
  {
    "_id": 3,
    "letter": "a"
  }
]

我希望通过letter属性合并所有这些项目,以便在最后有"bba"字符串(所以基本上只是这些字母的串联)。

我确实尝试阅读有关失败的mergeObjects ,因为string is not an object以及阅读其他可能的方法。 看起来我在这里遗漏了一些东西。

是否有可能返回这样的结果,也许有人可以帮助我了解如何返回?

非常感谢,祝您有美好的一天!

因此,在研究了一段时间之后,我想出了解决此类问题的方法。 在聚合管道中,我添加了:

  {
    $group: {
      _id: null,
      letters: {
        $push: "$letter"
      }
    }
  },
  {
    "$project": {
      _id: null,
      letters: {
        "$reduce": {
          "input": "$letters",
          "initialValue": "",
          "in": {
            "$concat": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM