Mongodb 按复杂的计算值对文档进行排序 [英] Mongodb sort documents by complex computed value

查看:29
本文介绍了Mongodb 按复杂的计算值对文档进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 已经存储在文档中,

The total_score and total_votes have stored in the document,

我可以按预期获得 temp_score 和 temp_votes,但无法获得体重,有什么建议吗?

I can get temp_score and temp_votes as expected, but can't get weight, any suggestion?

推荐答案

您的 $temp_score$temp_votes 尚不存在于您的 $divide.

Your $temp_score and $temp_votes are not existing yet in your $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"]
        }
    }
}])

或重新计算 $divide 中的 temp_scoretemp_votes :

or re-computing temp_score and 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] }
            ]
        }
    }
}]);

您也可以使用 $project 中完成此操作"nofollow noreferrer">$let 运算符 将用于创建 2 个变量 temp_scoretemp_votes.但是可以在单个字段下访问结果(此处为 total):

You can also do this in one single $project using the $let operator that will be used to create 2 variables temp_score and temp_votes. But the results will be accessible under a single field (here 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"] }
                }
            }
        }
    }
}])

这篇关于Mongodb 按复杂的计算值对文档进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆