首页 > 解决方案 > 如何在 find 方法中使用计算字段和条件进行查询?

问题描述

我真的不知道如何做到这一点。基本上在我的文档中我有一个费率,我想找到计算出的费率低于某个值的文档。计算的费率如下:

if (rate < 20) {
    calculated_rate = rate * 1.25;
} else {
    calculated_rate = rate + 5;
}

标签: mongodbmongodb-query

解决方案


aggregate(
    [
        { 
            "$addFields" : { 
                "calculated_rate" : { 
                    "$cond" : [
                        { 
                            "$lt" : [
                                "$AreasServedRateAndConditions.CGHourlyRate", 
                                20.0
                            ]
                        }, 
                        { 
                            "$multiply" : [
                                "$AreasServedRateAndConditions.CGHourlyRate", 
                                1.25
                            ]
                        }, 
                        { 
                            "$add" : [
                                "$AreasServedRateAndConditions.CGHourlyRate", 
                                5.0
                            ]
                        }
                    ]
                }
            }
        }, 
        { 
            "$match" : { 
                "$and" : [
                    { 
                        "calculated_rate" : { 
                            "$lte" : 25.0
                        }
                    }
                ]
            }
        }
    ], 
    { 
        "allowDiskUse" : false
    }
);

推荐阅读