列出年份创建的新办事处

问题描述 投票:0回答:1

我有一个包含 Office 许可证购买列表的集合。

在该列表中,我需要计算每年创建了多少个办事处。

我通过最早的许可对象知道这一点。

由于 OfficeId 是唯一的,如果我有多个 Office 许可证对象,我只需计算最旧的一个即可。这意味着在数据库中创建该 Office 的年份。

所以我有:

[
  {
    "_id": "514de62f-0a4c-46c8-ba66-5692935f0930",
    "OfficeId": "09ac58f0-8d2a-42ec-ba47-f518dd9d0904",
    "PlanName": "Plan 50",
    "PlanPrice": 777,
    "PaidValue": 330,
    "CreationDate": {
      "$date": "2017-03-08T03:00:00.000Z"
    },
    "Status": 1
  },
  {
    "_id": "e41a5923-3a69-43bb-87a4-f1169e172e2e",
    "OfficeId": "9679fdf7-02a1-4a1f-b0f0-17d3505e86e3",
    "PlanName": "Plan 50",
    "PlanPrice": 777,
    "PaidValue": 330,
    "CreationDate": {
      "$date": "2019-03-08T03:00:00.000Z"
    },
    "Status": 1
  },
  {
    "_id": "d314a8bf-0147-4aee-8357-f36db686c85a",
    "OfficeId": "eab54926-0c11-4c9f-aee2-7fbeabad4135",
    "PlanName": "Plan 50",
    "PlanPrice": 777,
    "PaidValue": 330,
    "CreationDate": {
      "$date": "2021-03-08T03:00:00.000Z"
    },
    "Status": 2
  }
]

预期结果:

[
 {CreationYear: 2018, NewOffices: 1},
 {CreationYear: 2019, NewOffices: 1},
 {CreationYear: 2021, NewOffices: 1}
]
mongodb aggregation-framework
1个回答
0
投票
  1. $group
    - 按
    OfficeId
    分组并获取最早的
    CreationDate

  2. $group
    - 按
    OfficeCreationDate
    的年份分组并执行计数。

  3. $project
    - 装饰输出文档。

  4. $sort
    (可选)- 按
    CreationYear
    升序排列文档。

db.collection.aggregate([
  {
    $group: {
      _id: "$OfficeId",
      OfficeCreationDate: {
        $min: "$CreationDate"
      }
    }
  },
  {
    $group: {
      _id: {
        $year: "$OfficeCreationDate"
      },
      NewOffice: {
        $count: {}
      }
    }
  },
  {
    $project: {
      _id: 0,
      CreationYear: "$_id",
      NewOffice: "$NewOffice"
    }
  },
  {
    $sort: {
      CreationYear: 1
    }
  }
])

演示@Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.