我试图用嵌套的子文档计算数据,但我无法理解如何得到我想要的东西(如果可能的话)。
我有以下mongoose模式,用于约会列表:
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,
}
]
}
}
答案 0 :(得分:0)
以下聚合查询将为您提供类似的结果:
db.appointments.aggregate(
[
{
$group: {
_id: "$clinic",
count: { $push: "$type" }
}
},
{
$project:{
_id: 0,
id: "$_id._id",
name: "$_id.name",
"count": 1
}
}
]
).pretty();
示例输出:
{
"count" : [
{
"_id" : ObjectId("583ecd06401ce04a0ca7e170"),
"name" : "Appointment Type 1"
},
{
"_id" : ObjectId("583ecd09401ce04a0ca7e171"),
"name" : "Appointment Type 2"
},
{
"_id" : ObjectId("583ecd0c401ce04a0ca7e172"),
"name" : "Appointment Type 3"
}
],
"id" : ObjectId("583eccf6401ce04a0ca7e16d"),
"name" : "Clinic 1"
}
{
"count" : [
{
"_id" : ObjectId("583ecd06401ce04a0ca7e170"),
"name" : "Appointment Type 1"
},
{
"_id" : ObjectId("583ecd0c401ce04a0ca7e172"),
"name" : "Appointment Type 3"
}
],
"id" : ObjectId("583eccfd401ce04a0ca7e16e"),
"name" : "Clinic 2"
}
{
"count" : [
{
"_id" : ObjectId("583ecd06401ce04a0ca7e170"),
"name" : "Appointment Type 1"
}
],
"id" : ObjectId("583ecd01401ce04a0ca7e16f"),
"name" : "Clinic 3"
}
count: 4
中的count
与{1}}有什么关系?