Mongodb 按复数计算值对文档排序
Mongodb sort documents by complex computed value
items = collection.aggregate([
{"$match": {}},
{"$project": {
'temp_score': {
"$add": ["$total_score", 100],
},
'temp_votes': {
"$add": ["$total_votes", 20],
},
'weight': {
"$divide": ["$temp_score", "$temp_votes"]
}
}
}
])
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"]
}
}
}])
或重新计算 temp_score
和 temp_votes
in $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] }
]
}
}
}]);
您也可以使用将用于创建 2 个变量 temp_score
和 temp_votes
的 $let
operator 在单个 $project
中执行此操作。但结果将在单个字段下访问(此处 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"] }
}
}
}
}
}])
items = collection.aggregate([
{"$match": {}},
{"$project": {
'temp_score': {
"$add": ["$total_score", 100],
},
'temp_votes': {
"$add": ["$total_votes", 20],
},
'weight': {
"$divide": ["$temp_score", "$temp_votes"]
}
}
}
])
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"]
}
}
}])
或重新计算 temp_score
和 temp_votes
in $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] }
]
}
}
}]);
您也可以使用将用于创建 2 个变量 temp_score
和 temp_votes
的 $let
operator 在单个 $project
中执行此操作。但结果将在单个字段下访问(此处 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"] }
}
}
}
}
}])