如何使用mongo聚合将两个或多个字段分组以找到不同的字段

时间:2020-10-16 05:56:50

标签: mongodb

我的约会文档如下

[{
    "_id" : ObjectId("5f25686c946376355468caab"),
    "status" : "approved",
    "slot" : ObjectId("5ee751ab85596308c0272fa2"),
    "student" : ObjectId("5eddc7d7cc5d3608c0393ce1"),
    "teacher" : ObjectId("5eccfd6d4f5d8d48ac567a5d"),
    "cost" : 49,
    "createdAt" : ISODate("2020-08-01T13:04:44.696Z"),
    "updatedAt" : ISODate("2020-08-01T13:20:36.164Z"),
    "decisionTime" : ISODate("2020-08-01T13:20:36.161Z")
},
{
    "_id" : ObjectId("5f25687b946376355468caac"),
    "status" : "approved",
    "slot" : ObjectId("5ee751ab85596308c0272fa3"),
    "student" : ObjectId("5eddc7d7cc5d3608c0393ce1"),
    "teacher" : ObjectId("5eccfd6d4f5d8d48ac567a5d"),
    "cost" : 49,
    "createdAt" : ISODate("2020-08-01T13:04:59.125Z"),
    "updatedAt" : ISODate("2020-08-01T13:06:12.289Z"),
    "decisionTime" : ISODate("2020-08-01T13:06:12.288Z")
},
{
    "_id" : ObjectId("5f2ad883f0971a0c3c7d6e6f"),
    "status" : "approved",
    "slot" : ObjectId("5ee751ab85596308c0272fa4"),
    "student" : ObjectId("5eddc7f4cc5d3608c0393ce3"),
    "teacher" : ObjectId("5eccfd6d4f5d8d48ac567a5d"),
    "cost" : 49,
    "createdAt" : ISODate("2020-08-05T16:04:19.437Z"),
    "updatedAt" : ISODate("2020-08-05T16:04:52.616Z"),
    "decisionTime" : ISODate("2020-08-05T16:04:52.615Z")
}]

我想使用mongo聚合对特定日期的特定学生总数,约会总数,特定日期的总成本(createdAt)进行分组。 如何在不同的日期获得杰出学生

预期输出:

[
  {
    "_id": "01-08-2020",
    "appointments": 2,
    "totalCost": 98,
    "totalStudents": 1
  },
  {
    "_id": "05-08-2020",
    "appointments": 1,
    "totalCost": 49,
    "totalStudents": 1
  }
]

这里的问题是我想找到不同学生的总数

1 个答案:

答案 0 :(得分:2)

Group by createdAt字段的天,月和年,只需使用$dateFromParts运算符,然后将cost字段加起来即可。

要获得独特的学生领域,请使用$addToSet运算符,并在分组时将其推入一个集合中,在项目阶段只需投影该集合中的size

还可以根据您的要求createdAt设置%d-%m-%Y字段$dateToString的格式。

db.collection.aggregate([
  {
    $group: {
      _id: {
        $dateFromParts: {
            day: {
                $dayOfMonth: '$createdAt'
            },
            month: {
                $month: '$createdAt'
            },
            year: {
                $year: '$createdAt'
            }
        }
      },
      createdAt: {
        $first: '$createdAt'
      },
      totalAppointments: {
        $sum: 1
      },
      totalCost: {
        $sum: '$cost'
      },
      students: {
        $addToSet: '$student'
      }
    }
  },
  {
    $project: {
      _id: {
        $dateToString: {
          date: '$createdAt',
          format: '%d-%m-%Y'
        }
      },
      appointments: '$totalAppointments',
      totalCost: '$totalCost',
      totalStudents: {
        $size: '$students'
      }
    }
  }
]);

提供输出:

[
  {
    "_id": "05-08-2020",
    "appointments": 1,
    "totalCost": 49,
    "totalStudents": 1
  },
  {
    "_id": "01-08-2020",
    "appointments": 2,
    "totalCost": 98,
    "totalStudents": 1
  }
]

MongoDb playground