【问题标题】:Group nested field in mongo documents在 mongo 文档中分组嵌套字段
【发布时间】:2021-06-20 22:05:34
【问题描述】:

我的 MongoDB 数据库中有以下文档的结构:

[
  {
    name: "x1",
    stages: [
      {
        _id: "60cb49c4977b0c64f2667054",
        type: "y1"
      },
      {
        _id: "60cb49c4977b0c64f2667055",
        type: "y2"
      },
      ...
    ]
  },
  {
    name: "x2",
    stages: [
      {
        _id: "60cb49c4977b0c64f2667054",
        type: "y1"
      },
      {
        _id: "60cb49c4977b0c64f2667055",
        type: "y2"
      },
      ...
    ]
  },
  
]

我想在每个主文档(namex1,x2,... 的那些)和 stages 按他们的类型(y1,y2,...)分组,所以基本上是嵌套的组操作。

这是我希望使用聚合方法得到的预期结果:

[
  {
    name: "x1",
    stages: [
      {
        type: "y1",
        stages: [
          {
            _id: "60cb49c4977b0c64f2667054",
            type: "y1"
          }
        ]
      },
      {
        type: "y2",
        stages: [
          {
            _id: "60cb49c4977b0c64f2667055",
            type: "y2"
          }
        ]
      }
    ]
  },
{
    name: "x2",
    stages: [
      {
        type: "y1",
        stages: [
          {
            _id: "60cb49c4977b0c64f2gggg667054",
            type: "y1"
          }
        ]
      },
      {
        type: "y2",
        stages: [
          {
            _id: "60cb49c4977b0c64f2tttt667055",
            type: "y2"
          }
        ]
      }
    ]
  }
]

有什么帮助吗?我不知道如何继续我的聚合方法(这个快照代码是我成功编写预代码聚合的格式)

【问题讨论】:

  • 您认为提供的答案中是否有某些内容无法解决您的问题?如果是这样,那么请对答案发表评论,以阐明究竟需要解决哪些尚未解决的问题。

标签: mongodb aggregation-framework


【解决方案1】:
  • $unwind解构stages数组
  • $group by _id and stage type 获取名字字段并构造stages的数组
  • $group 仅通过 _id 获取名字字段并使用 type 字段和 stages 子数组重构 stages 数组
db.collection.aggregate([
  { $unwind: "$stages" },
  {
    $group: {
      _id: {
        _id: "$_id",
        type: "$stages.type"
      },
      name: { $first: "$name" },
      stages: { $push: "$stages" }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      name: { $first: "$name" },
      stages: {
        $push: {
          type: "$_id.type",
          stages: "$stages"
        }
      }
    }
  }
])

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 2021-07-20
    • 2011-11-04
    • 1970-01-01
    相关资源
    最近更新 更多