问题描述
假定以下记录:
{ text: "foo"},
{ text: "bar"}
如何获得如下结果:
results: "foo bar"
我最接近的是使用 $ addToSet
,但这只会创建一个带有结果的数组,而不是我真正想要的单个字符串.
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" ]
使用Mongo 3.4
Using Mongo 3.4
推荐答案
使用 $ group 从所有文档中获取一个数组,然后 $ reduce 与 $concat 获得一个字符串:
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" ] } ]
}
}
}
}
}
])
在 $ group
之后,您将获得一个包含所有 text
值的数组的单个文档.然后 $ reduce
扫描"数组并将状态( $$ value
)与当前处理的项目连接在一起.对于第一个项目,状态将是一个空字符串,因此我在使用 $ cond
以避免开头出现空格.
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.
这篇关于如何将来自多个MongoDB记录的字符串结果串联到MongoDB中的单个结果中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!