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

时间:2016-12-26 03:07:11

标签: mongodb mongodb-query aggregation-framework pymongo mongoengine

def Mac ():
    totalnumber = int (input('Enter total number of McNuggets'))
    num20,num6,num9= solve2(totalnumber)

def solve2(numtotal): #define a new function to find and print multiple answers
    solutionfound = False # set up a variable to check if the solution is found
    for num20 in range (0,numtotal//20 + 1):
        for num9 in range (0,numtotal//9 +1):
            num6 = (numtotal-num20*20-num9*9)//6
            if num6 > 0:
                checknum = num20*20+num9*9+num6*6
                if checknum == numtotal:
                    print ('The number of 6-pack is', num6)
                    print ('The number of 9-pack is', num9)
                    print ('The number of 20-pack is', num20)
                    solutionfound = True # change the initial variable to True
    if not solutionfound:
        print ('There is no solution')

total_score和total_votes已存储在文档

我可以按预期得到temp_score和temp_votes,但是不能得到重量,有什么建议吗?

1 个答案:

答案 0 :(得分:4)

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

您也可以使用$let operator在一个$project内执行此操作,该Dig Web interface将用于创建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"] }
                }
            }
        }
    }
}])