$temp_score của bạn và $temp_votes chưa tồn tại trong $divide của bạn .
Bạn có thể thực hiện một $project khác :
db.user.aggregate([{
"$project": {
'temp_score': {
"$add": ["$total_score", 100],
},
'temp_votes': {
"$add": ["$total_votes", 20],
}
}
}, {
"$project": {
'temp_score':1,
'temp_votes':1,
'weight': {
"$divide": ["$temp_score", "$temp_votes"]
}
}
}])
hoặc tính toán lại temp_score và temp_votes trong $divide :
db.user.aggregate([{
"$project": {
'temp_score': {
"$add": ["$total_score", 100],
},
'temp_votes': {
"$add": ["$total_votes", 20],
},
'weight': {
"$divide": [
{ "$add": ["$total_score", 100] },
{ "$add": ["$total_votes", 20] }
]
}
}
}]);
Bạn cũng có thể thực hiện việc này trong một $project bằng cách sử dụng $let nhà điều hành
sẽ được sử dụng để tạo 2 biến temp_score và temp_votes . Nhưng kết quả sẽ có thể truy cập được trong một trường duy nhất (tại đây total ):
db.user.aggregate([{
$project: {
total: {
$let: {
vars: {
temp_score: { $add: ["$total_score", 100] },
temp_votes: { $add: ["$total_votes", 20] }
},
in : {
temp_score: "$$temp_score",
temp_votes: "$$temp_votes",
weight: { $divide: ["$$temp_score", "$$temp_votes"] }
}
}
}
}
}])