smorhaim
smorhaim

Reputation: 798

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

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

Upvotes: 1

Views: 1732

Answers (1)

mickl
mickl

Reputation: 49945

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.

Upvotes: 7

Related Questions