如何使用猫鼬的条件按特定年份分组

时间:2015-12-07 09:27:15

标签: node.js mongodb mongoose

我必须使用mongoose group by和aggregate函数计算特定的年份数,但是我没有使用条件来分组特定年份,我必须使用下面的代码,

Opp.aggregate([
    {$project:{
    _id: {year: {$year: '$HireDate'}},
    hireDateValue: {year: {$year: '$HireDate'}},
    hireDateCount: {$cond: [{"$and":[{"$or":[{"$eq":["$HireDate","1994-01-17 00:00:00.000"]}]}]}, 1, 0]}
    }},
    {$group: { _id: '$hireDateValue', count: {$sum: '$hireDateCount'} }},
    {$sort: {_id: 1}}
    ], function (err, dateResult) {
    resultAggr[0].items = dateResult;
    res.send([resultAggr]);
    }); 

我的回复,

[

    [
        {
            "id":7,
            "_id":"HiredDate",
            "items":[
                {...},
                {
                    "_id":{
                        "year":1990
                    },
                    "count":0
                },
                {
                    "_id":{
                        "year":1991
                    },
                    "count":0
                },
                {
                    "_id":{
                        "year":1992
                    },
                    "count":0
                },
                {
                    "_id":{
                        "year":1993
                    },
                    "count":0
                },
                {
                    "_id":{
                        "year":1994
                    },
                    "count":0
                },{...}
            ],
            "expanded":true
        }
    ]

]

请帮助在分组特定年份时如何使用条件,

1 个答案:

答案 0 :(得分:2)

您要对hireDateCount做什么?

您的查询正在尝试计算HireDate的总数,其中HireDate是" 1994-01-17 00:00:00.000"和按年分组

如果您想计算雇佣人数,请逐年分组

Opp.aggregate([
    {$project:{
        _id: {year: {$year: '$HireDate'}},
        hireDateValue: {year: {$year: '$HireDate'}}
    }},
    {$group: { _id: '$hireDateValue', count: {$sum: 1 } }},
    {$sort: {_id: 1}}
    ], function (err, dateResult) {
       resultAggr[0].items = dateResult;
       res.send([resultAggr]);
});

或2015年的雇佣人数(过滤HiredDate低于2016年,大于或等于2015年)

Opp.aggregate([
    { $match: { HiredDate: { $lt: new Date("2016-01-01"), $gte: new Date("2015-01-01") } } },
    {$project:{
        _id: {year: {$year: '$HireDate'}},
        hireDateValue: {year: {$year: '$HireDate'}}
    }},
    {$group: { _id: '$hireDateValue', count: {$sum: 1 } }},
    {$sort: {_id: 1}}
    ], function (err, dateResult) {
       resultAggr[0].items = dateResult;
       res.send([resultAggr]);
});

希望有所帮助