问题
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