我收到错误:
“无法识别的表达式'$ addFields'”
当我尝试使用MongoDB聚合框架计算数组中字段的平均值时。
有人可以帮我理解下面的代码段中的错误。
我的数据库版本是3.4.5
"doctor": {
"$map": {
"input": "$$procedure.doctor",
"as": "doctor",
"in": {
"$cond": [//specify the filter for doctor
{
"$eq": ["$$doctor.activeFlag", "Y"]
},
{
"doctorName": "$$doctor.doctorName",
"DoctorUserRating": {
"$map": {
"input": "$$doctor.DoctorUserRating",
"as": "docUserRate",
"in": {
"$cond": [//specify the filter for user rating
{},
{
//Calculate the average of userRating from array
"$addFields": {
"avarageDocRating": {
"$divide": [
{ // expression returns total
"$reduce": {
"input": "$$docUserRate",
"initialValue": 0,
"in": { "$add": ["$$value", "$$this.userRating"] }
}
},
{ // expression returns ratings count
"$cond": [
{ "$ne": [{ "$size": "$$docUserRate" }, 0] },
{ "$size": "$$docUserRate" },
1
]
}
]
}
},
//////////////////////
},
false
],
},//"in": {
},//"$map": {
},//"DoctorUserRating": {
},
false
],
},//"in": {
},//"$map": {
},//"doctor":
我的模特是
hospitalName: { type: String, required: true, trim: true },
hospitalID: { type: Number, required: true, unique: true, dropDups: true },
serviceActiveFlag: { type: String, required: true, enum: ['Y', 'N'] },//new
Treatment: [{
procedureid: { type: Number },
costUpperBound: { type: Number, required: true },
doctor: [{
doctorId: { type: Number},
doctorName: { type: String, required: true, trim: true },
DoctorUserRating:[ {
userRating:{type: Number, required: true, //To get default rating for cost api
min: [1, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'],
max: [5, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']
},
userId: { type: String, required: false, trim: true},
}],
}],
}],
updated_at: { type: D
吃,必需:true,默认:Date.now}
答案 0 :(得分:0)
我找到了解决方案 -
"DoctorUserRating": {
"$map": {
"input": "$$doctor.DoctorUserRating",
"as": "docUserRate",
"in": {
"$cond": [//specify the filter for user rating
{},
{
"averageDocRate": { "$avg": "$$docUserRate.userRating" }
},
}