如何正确查询以获取当前数据格式所需的统计数据? (mongoDB/NoSQL)

How do i query properly to get the statistical data I need with current data format? (mongoDB / NoSQL)

我一直在努力寻找一种方法来获取我需要与其他部门共享的统计数据。

这是 MongoDB 中的当前文档示例。

{
date : ‘2021-09-10T12:00:00+09:00’,
Category : ‘usedCar’,
Data : [
    {name : ‘bmw’, theNumberOfSold : 15},
    {name : ‘Honda’, theNumberOfSold : 35},
    {name : ‘Toyota’, theNumberOfSold : 100}…….
] 
}

{
date : ‘2021-09-11T12:00:00+09:00’,
Category : ‘newCar’,
Data : [
    {name : ‘bmw’, theNumberOfSold : 5},
    {name : ‘Honda’, theNumberOfSold : 8},
    {name : ‘Toyota’, theNumberOfSold : 150}…….
] 
}

我想得到如下结果。 mongodb聚合查询是否可行?一整天都试了很多方法都没有..

-2021 年 9 月,按已售出数量排序的二手车名称列表 -2021年1月~7月,新车按名称排序,按销量排序

the way I am going to utilize extracted data

  • $unwind 展开数据
  • $group按月、年、名分组
db.collection.aggregate([
  {
    $unwind: "$Data"
  },
  {
    $group: {
      _id: {
        year: {
          "$year": "$date"
        },
        month: {
          "$month": "$date"
        },
        name: "$Data.name"
      },
      totalAmount: {
        $sum: "$Data.theNumberOfSold"
      }
    }
  }
])

mongoplayground