Mongodb 按复杂的计算值对文档进行排序

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,但无法获得体重,有什么建议吗?

Ber*_*tel 5

您的$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_scoretemp_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_scoretemp_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)