Mongodb sort documents by complex computed value

僤鯓⒐⒋嵵緔 提交于 2019-12-04 04:46:39

问题


items = collection.aggregate([
        {"$match": {}},
        {"$project": {
            'temp_score': {
                "$add": ["$total_score", 100],
            },
            'temp_votes': {
                "$add": ["$total_votes", 20],
            },
            'weight': {
                "$divide": ["$temp_score", "$temp_votes"]
            }

            }
        }
    ])

The total_score and total_votes have stored in the document,

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


回答1:


Your $temp_score and $temp_votes are not existing yet in your $divide.

You can do another $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"]
        }
    }
}])

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] }
            ]
        }
    }
}]);

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"] }
                }
            }
        }
    }
}])


来源:https://stackoverflow.com/questions/41326073/mongodb-sort-documents-by-complex-computed-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!