0
我想用嵌套的子文檔計數數據,我無法理解我如何得到我想要的(以及是否可能)。從mongodb中的子文檔計數數據與貓鼬
我有用於約會列表如下貓鼬模式:
var AppointmentSchema = new mongoose.Schema(
\t {
\t \t clinic: {
\t \t \t type: mongoose.Schema.Types.ObjectId,
\t \t \t ref: 'Clinic',
\t \t \t required: true,
\t \t },
\t \t type: {
\t \t \t type: mongoose.Schema.Types.ObjectId,
\t \t \t ref: 'AppointmentType',
\t \t \t required: true,
\t \t }
\t }
);
var ClinicSchema = new mongoose.Schema(
\t {
\t \t name: {
\t \t \t type: String,
\t \t \t maxlength: 25,
\t \t \t required: true,
\t \t }
\t }
);
var AppointmentTypeSchema = new mongoose.Schema(
\t {
\t \t name: {
\t \t \t type: String,
\t \t \t minlength: 2,
\t \t \t maxlength: 25,
\t \t \t required: true,
\t \t }
\t }
);
從約會的那個名單,我期待報告度量知道不同數量每個診所的預約類型。
到目前爲止,我只能夠使用下面的聚集,讓每類任用的計數不管診所:
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
但我想獲得情況如下內容:
{
\t {
\t \t id: 1,
\t \t name: "Name of the cliniC#1",
\t \t count: [
\t \t \t {
\t \t \t \t id: 10,
\t \t \t \t name: "Appointment Type #10",
\t \t \t \t count: 4,
\t \t \t },
\t \t \t {
\t \t \t \t id: 20,
\t \t \t \t name: "Appointment Type #20",
\t \t \t \t count: 1,
\t \t \t }
\t \t ]
\t },
\t {
\t \t id: 2,
\t \t name: "Name of the cliniC#2",
\t \t count: [
\t \t \t {
\t \t \t \t id: 10,
\t \t \t \t name: "Appointment Type #10",
\t \t \t \t count: 5,
\t \t \t },
\t \t \t {
\t \t \t \t id: 20,
\t \t \t \t name: "Appointment Type #20",
\t \t \t \t count: 2,
\t \t \t }
\t \t ]
\t }
}