How to concatenate string results from multiple MongoDB records into a single result in MongoDB?

删除回忆录丶 提交于 2021-02-15 07:12:16

问题


Assuming the following records:

{ text: "foo"},
{ text: "bar"}

How can I get a result such as:

results: "foo bar"

The closest I am getting to it is to use $addToSet but this just creates an array with the results instead of a single string which is what I really want.

results: [ "foo", "bar" ] 

Using Mongo 3.4


回答1:


Use $group to get an array from all the documents and then $reduce with $concat to get one string:

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

After $group you will get single document which contains an array of all text values. Then $reduce "scans" the array and concatenates the state ($$value) with currently processed item. For the first item state will be an empty string so I'm using $cond to avoid having whitespace on the beginning.



来源:https://stackoverflow.com/questions/55838681/how-to-concatenate-string-results-from-multiple-mongodb-records-into-a-single-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!