【问题标题】:how to project the nested array as individual object with total count in mongodb如何在mongodb中将嵌套数组投影为具有总数的单个对象
【发布时间】:2021-04-10 04:55:57
【问题描述】:

我有一个这样的集合,我需要展开数组并返回总数。我还需要在结果集中跳过和限制。非常感谢输入的任何帮助

[
  {
    "a": "b",
    xyz: [
      {
        "c": "d"
      },
      {
        "e": "f"
      }
    ]
  },
  {
    "g": "h",
    xyz: [
      {
        "i": "j"
      },
      {
        "k": "l"
      }
    ]
  }
]

预期输出

[
  {
    "xyz": {
      "c": "d"
    }
  },
  {
    "xyz": {
      "e": "f"
    }
  },
  {
    "xyz": {
      "i": "j"
    }
  },
  {
    "xyz": {
      "k": "l"
    }
  },
  "totalCount": 4
]

我还需要对上面的结果数据集进行分页功能

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:
    • $project 显示必填字段
    • $unwind解构xyz数组
    • $facet 将结果和计数分开
    • $skip 跳过文档数
    • $limit 限制文档数量
    • $arrayElemAttotalCount 数组中获取第一个元素
    db.collection.aggregate([
      { $project: { xyz: 1 } },
      {
        $unwind: "$xyz"
      },
      {
        $facet: {
          result: [
            { $skip: 0 },
            { $limit: 10 }
          ],
          totalCount: [
            { $count: "totalCount" }
          ]
        }
      },
      {
        $addFields: {
          totalCount: {
            $arrayElemAt: ["$totalCount.totalCount", 0]
          }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 2015-05-12
      • 1970-01-01
      • 2021-04-16
      • 2016-02-14
      • 2021-12-16
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      相关资源
      最近更新 更多