首页 > 解决方案 > 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 集合以获取上述结果或以任何其他方式生成具有所需结果的集合并将其作为响应发送。

标签: mongodb

解决方案


  1. $groupparagraph-按$push text数组字段 ( )分组texts
  2. $project- 装饰输出文件。用于$reduce$concat texts字段排列成字符串。并且不要忘记使用$trim删除起始空格。
  3. $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
    }
  }
])

示例 Mongo Playground


推荐阅读