MongoDB:mongodb中使用 $cond条件来完成类似case when then的功能

exports.sumByGSAsync = function (opts) {
    var results = {error_code: -1, error_msg: "error"};
    var beginDate=opts.beginDate;
    var endDate=opts.endDate;
    var pipeline =[
        {
            $match: {
                sjbh: {$gte: beginDate, $lte:endDate}
            }
        },
        {
            $group: {
                _id:  "$gsbh",
                totaltxl: {$sum: { $cond: { if: { $ne: [ "$totalnum","" ] }, then:"$txl" , else: 0 }}},
                totalbmynum: {$sum: "$bmynum"}
            }
        },
        {
            $project: {
                _id: 0,
                gsbh: "$_id",
                totaltxl: "$totaltxl",
                totalbmynum: "$totalbmynum",
                ratio: { $divide: [  "$totalbmynum", { $cond:{if: { $eq: [ "$totaltxl",0 ] }, then:1 , else: "$totaltxl" }}] }
            }
        },
        {$sort: {ratio: -1}}
    ];

    return opts.dbs.csdb.collection("permydfx").aggregateAsync(pipeline)
        .timeout(opts.configs.timeoutnormal)
        .then(function (value) {
    .....
        });
}

你可能感兴趣的:(mongodb,数据库)