【发布时间】:2016-11-30 21:13:27
【问题描述】:
我正在尝试使用嵌套子文档对数据进行计数,但我无法理解如何获得我想要的(如果可能的话)。
我有以下用于约会列表的猫鼬模式:
var AppointmentSchema = new mongoose.Schema(
{
clinic: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Clinic',
required: true,
},
type: {
type: mongoose.Schema.Types.ObjectId,
ref: 'AppointmentType',
required: true,
}
}
);
var ClinicSchema = new mongoose.Schema(
{
name: {
type: String,
maxlength: 25,
required: true,
}
}
);
var AppointmentTypeSchema = new mongoose.Schema(
{
name: {
type: String,
minlength: 2,
maxlength: 25,
required: true,
}
}
);
从预约列表中,我希望报告指标以了解每个诊所不同类型预约的数量。
到目前为止,无论诊所使用以下聚合,我都只能获得每种预约类型的计数:
db.appointments.aggregate(
[
{
$group: {
_id: '$type', //$type is the column name in collection
count: {$sum: 1}
}
},
{
$sort: { count: -1 }
}
]
);
这将返回以下结果:
{ "_id" : ObjectId("5838ef21b19aee730b8ae6c8"), "count" : 5 }
{ "_id" : ObjectId("5838efa4d695cb7839672417"), "count" : 3 }
{ "_id" : ObjectId("5838efb4d695cb7839672419"), "count" : 3
但我想得到如下:
{
{
id: 1,
name: "Name of the clinic #1",
count: [
{
id: 10,
name: "Appointment Type #10",
count: 4,
},
{
id: 20,
name: "Appointment Type #20",
count: 1,
}
]
},
{
id: 2,
name: "Name of the clinic #2",
count: [
{
id: 10,
name: "Appointment Type #10",
count: 5,
},
{
id: 20,
name: "Appointment Type #20",
count: 2,
}
]
}
}
【问题讨论】: