Conditional unwind in MongoDb's aggregation?

后端 未结 1 508
旧巷少年郎
旧巷少年郎 2021-02-06 13:54

I\'m trying to figure out if there is a way to code a conditional unwind in MongoDB\'s aggregation framework.

I have an aggregation command like this:

mo         


        
1条回答
  •  生来不讨喜
    2021-02-06 14:45

    Build up your aggregation pipeline programmatically prior to calling aggregate:

    var pipeline = [];
    pipeline.push(
        {   // SELECT
        $project : { "sex" : 1,
                 "salesIndex":1
                }
        },
        {   // WHERE
            $match: {"salesIndex": {$gte: index}}
        }
    );
    if (filteringByDepartment) {
        pipeline.push(
            { $unwind: '$departments' },
            { $match: { departments: departmentId }}
        );
    }    
    pipeline.push(
        {   // GROUP BY y agregadores
            $group: {
                _id      : "$sex",
                sexCount : { $sum: 1 }
            }
        },
        { $sort: { sexCount: -1 } }
    );
    
    models.Users.aggregate(pipeline, function(err, dbres) {
        //...
    });
    

    0 讨论(0)
提交回复
热议问题