在计算字段Mongodb上使用$ match

时间:2015-11-30 15:26:32

标签: mongodb

我在MongoDB中有这个聚合查询:

db.questions.aggregate([
{ $project:{question:1,detail:1, choices:1, answer:1,
  percent_false:{
  $multiply:[100,{$divide:["$answear_false",{$add:["$answear_false","$answear_true"]}]}]},
  percent_true:{
  $multiply:[100,{$divide:["$answear_true",{$add:["$answear_false","$answear_true"]}]}]}    }}, {$match:{status:'active'} } 
]).pretty()

我想在2个计算字段上使用$ match" percent_true"和" percent_false"像这样

$match : {percent_true:{$gte:20}}

我该怎么办?

1 个答案:

答案 0 :(得分:2)

当聚合框架分阶段工作时,您可以将计算字段视为正常字段,因为从$match的角度来看,它们是正常的。

{ $project:{
      question:1,detail:1, choices:1, answer:1,
      percent_false:{
        $multiply:[100,{$divide:["$answear_false",{$add:["$answear_false","$answear_true"]}]}]
      },
      percent_true:{
        $multiply:[100,{$divide:["$answear_true",{$add:["$answear_false","$answear_true"]}]}]}    
    }
}, 
{$match:{
    status:'active',
    percent_true:{$gte:20}
    //When documents get fed to match they already have a percent_true field, so you can match on them as normal
    } 
}