如何将多个 MongoDB 记录的字符串结果连接成 MongoDB 中的单个结果?

smo*_*aim 1 mongodb aggregation-framework

假设有以下记录:

{ text: "foo"},
{ text: "bar"}
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到如下结果:

results: "foo bar"
Run Code Online (Sandbox Code Playgroud)

我最接近的是使用,$addToSet但这只是创建一个包含结果的数组,而不是我真正想要的单个字符串。

results: [ "foo", "bar" ] 
Run Code Online (Sandbox Code Playgroud)

使用蒙戈3.4

mic*_*ckl 6

使用$group从所有文档中获取一个数组,然后使用$reduce$concat获取一个字符串:

db.col.aggregate([
    {
        $group: {
            _id: null,
            text: { $push: "$text" }
        }
    },
    {
        $project: {
            text: {
                $reduce: {
                    input: "$text",
                    initialValue: "",
                    in: {
                        $cond: [ { "$eq": [ "$$value", "" ] }, "$$this", { $concat: [ "$$value", " ", "$$this" ] } ]
                    }
                }
            }
        }
    }
])
Run Code Online (Sandbox Code Playgroud)

之后$group您将获得包含所有值的数组的单个文档text。然后$reduce“扫描”数组并将状态 ( $$value) 与当前处理的项目连接起来。对于第一个项目状态将是一个空字符串,因此我用来$cond避免开头有空格。