我的约会文档如下
[{
"_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
}
]
这里的问题是我想找到不同学生的总数
答案 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
}
]