列出最旧的注册表并获取状态

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

我有一个包含 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": "Active"
  },
  {
    "_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": "Active"
  },
  {
    "_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": "Inactive"
  },
  {
    "_id": "d314a8bf-0147-4aee-8357-f36db686c85a",
    "OfficeId": "eab54926-0c11-4c9f-aee2-7fbeabad4135",
    "PlanName": "Plan 100",
    "PlanPrice": 7776,
    "PaidValue": 3308,
    "CreationDate": {
      "$date": "2021-03-08T03:00:00.000Z"
    },
    "Status": "Active"
  }
]

预期结果:

[
 {CreationYear: 2017, NewOffices: 1, Active: 1},
 {CreationYear: 2019, NewOffices: 1, Active: 1},
 {CreationYear: 2021, NewOffices: 2, Active: 1}
]

请问我该如何处理?

mongodb aggregation-framework
1个回答
0
投票

你可以到年

$group
。对于每个组,办公室和活动状态计数相加。

db.collection.aggregate([
  {
    $group: {
      _id: { $year: "$CreationDate" },
      NewOffices: { $sum: 1 },
      Active: { $sum: { $cond: [ { $eq: [ "$Status", "Active" ] }, 1, 0 ] } }
    }
  },
  { $addFields: { CreationYear: "$_id" } },
  { $project: { _id: 0 } }
])

游乐场

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