mongo汇总框架按季度/半年/年分组

时间:2018-08-20 13:55:56

标签: mongodb group-by aggregation-framework

我有一个具有以下架构结构的数据库:

{
    "name" : "Carl",
    "city" : "paris",
    "time" : "1-2018",
    "notes" : [ 
        "A", 
        "A", 
        "B", 
        "C", 
        "D"
    ]
}

此查询使用聚合框架:

db.getCollection('collection').aggregate(
[{
    "$match": {
        "$and": [{
            "$or": [ {
                "time": "1-2018"
            }, {
                "time": "2-2018"
            } ]
        }, {
            "name": "Carl"
        }, {
            "city": "paris"
        }]
    }
}, {
    "$unwind": "$notes"
}, {
    "$group": {
        "_id": {
            "notes": "$notes",
            "time": "$time"
        },
        "count": {
            "$sum": 1
        }
    }
}
, {
    "$group": {
        "_id": "$_id.time",
        "count": {
            "$sum": 1
        }
    }
}, {
    "$project": {
                "_id": 0,
        "time": "$_id",
        "count": 1
    }
}])

它正常工作,我得到这些结果:

{
    "count" : 4.0,
    "time" : "2-2018"
}

{
    "count" : 4.0,
    "time" : "1-2018"
}

我的问题是我想保持相同的比赛阶段,我想按季度分组。

这里是我想要的结果:

{
    "count" : 8.0,
    "time" : "1-2018"  // here quarter 1
}

谢谢

0 个答案:

没有答案