通过复杂的计算值

问题描述:

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 MongoDB的排序文件都存储在文档中,通过复杂的计算值

我能得到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"] 
     } 
    } 
}]) 

或重新计算在$dividetemp_scoretemp_votes

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