问题描述
假设有以下记录:
{ text: "foo"},
{ text: "bar"}
我怎样才能得到这样的结果:
How can I get a result such as:
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 中的单个结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!