mongodb - MongoDB:使用公共字段过滤和合并文档
问题描述
假设我在 1 个集合中有 4 个文档
{
id: 1,
text: "Some text",
paragraph: 1
}
{
id: 2,
text: "This has field paragraph 2",
paragraph: 2
}
{
id: 3,
text: "This also has paragraph 2 field",
paragraph: 2
}
{
id: 4,
text: "Some other text",
paragraph: 3
}
过滤器结果的期望输出必须是
{
id: 1,
text: "Some text",
paragraph: 1
}
{
id: 2,
text: "This has field paragraph 2 This also has paragraph 2 field",
paragraph: 2
}
{
id: 3,
text: "Some other text",
paragraph: 3
}
如何过滤 mongodb 集合以获取上述结果或以任何其他方式生成具有所需结果的集合并将其作为响应发送。
解决方案
$group
paragraph
-按$push
text
数组字段 ( )分组texts
。$project
- 装饰输出文件。用于$reduce
将$concat
texts
字段排列成字符串。并且不要忘记使用$trim
删除起始空格。$sort
- 按id
升序排序。
db.collection.aggregate([
{
$group: {
_id: "$paragraph",
texts: {
"$push": "$text"
}
}
},
{
$project: {
_id: 0,
id: "$_id",
paragraph: "$_id",
text: {
$trim: {
input: {
$reduce: {
"input": "$texts",
"initialValue": "",
"in": {
$concat: [
"$$value",
" ",
"$$this"
]
}
}
}
}
}
}
},
{
$sort: {
id: 1
}
}
])
推荐阅读
- c# - 如何通过检查第一个值来存储多维数组的一维值?
- python - 在字符串列python上求和
- django - 在 django 内的 d3.js 中加载 .csv 文件不起作用
- reactjs - 在 React 中关注(滚动到)一个 DIV 元素
- python-3.x - 如何使用变量剥离()和拆分()?
- android - 任务“:react-native-camera:compileDebugJavaWithJavac”执行失败
- php - Zoho Crm API2 Created_By & Modifed_BY 未按请求更新
- mongodb - Mongo聚合:查找后的排序阶段和展开太慢
- c# - Bot:如何在 Bot 框架中使字段只读
- python - 张量流 TypeError 和 ValueError