Cl0*_*0ne 3 mongodb pymongo mongoengine mongodb-query aggregation-framework
items = collection.aggregate([
{"$match": {}},
{"$project": {
'temp_score': {
"$add": ["$total_score", 100],
},
'temp_votes': {
"$add": ["$total_votes", 20],
},
'weight': {
"$divide": ["$temp_score", "$temp_votes"]
}
}
}
])
Run Code Online (Sandbox Code Playgroud)
total_score 和 total_votes 已经存储在文档中,
我可以按预期获得 temp_score 和 temp_votes,但无法获得体重,有什么建议吗?
您的$temp_score和$temp_votes尚不存在于您的$divide.
你可以做另一个$project:
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"]
}
}
}])
Run Code Online (Sandbox Code Playgroud)
或重新计算temp_score并temp_votes在$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] }
]
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
你也可以这样做在一个单一的$project使用$let操作将被用来创建2个变量temp_score和temp_votes。但是可以在单个字段(此处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"] }
}
}
}
}
}])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
581 次 |
| 最近记录: |