MongoDB Group Aggregation中的多个累加器查询日,周,月和年

我正试图将我的数据按日,周,月和年分组在单个堆积线中。我在单独的字段中有日期,星期数,月份和年份。但是我无法弄清楚如何在单个流程中进行组聚合。 下面是示例json:

{ 
    "Ctrans" : {
    "status" : "active"
    },"Day-month" : "25-9","Month" : 9,"Year" : 2019,"Week" : 38
} 

我对此管道的查询:

db.getcollection("transaction").aggregate(
    [
        { 
            "$lookup" : {
                "from" : "customer","localField" : "pB.phone","foreignField" : "phone","as" : "Ctrans"
            }
        },{ 
            "$unwind" : {
                "path" : "$Ctrans","includeArrayIndex" : "arrayIndex","preserveNullAndEmptyArrays" : false
            }
        },{ 
            "$project" : {
                "date" : {
                    "$dateFromString" : {
                        "dateString" : "$createdAt","onError" : "$date"
                    }
                },"Weekdate" : {
                    "$dateFromString" : {
                        "dateString" : "$createdAt","Ctrans.status" : 1.0,"createdAt" : 1.0
            }
        },{ 
            "$project" : {
                "date" : {
                    "$dateToParts" : {
                        "date" : "$date"
                    }
                },"week" : {
                    "$week" : "$Weekdate"
                },"Ctrans.status" : 1.0
            }
        },{ 
            "$project" : {
                "Day-month" : {
                    "$concat" : [
                        {
                            "$toString" : "$date.day"
                        },"-",{
                            "$toString" : "$date.month"
                        }
                    ]
                },"Month" : "$date.month","Year" : "$date.year","Week" : "$week",{ 
            "$group" : {
                "_id" : {
                    "Today" : "$Day-month","Status" : "$status"
                },"Total" : {
                    "$sum" : 1.0
                }
            }
        }
    ],{ 
        "allowDiskUse" : false
    }
);

我旨在通过(Day-month,status),(month,(year,(week,status)对进行分组,并分别获取每个配对组的 count

einspei 回答:MongoDB Group Aggregation中的多个累加器查询日,周,月和年

您可以使用$facet在数据集上应用单独的$group阶段,请尝试:

db.collection.aggregate([
    // current aggregation stages,{
        $facet: {
            "dayMonthStatus": [
                { $group: { _id: { status: "$Ctrans.status","dayMonth": "$Day-month" },count: { $sum: 1 } } }
            ],"monthStatus": [
                { $group: { _id: { status: "$Ctrans.status","month": "$Month" },"yearStatus": [
                { $group: { _id: { status: "$Ctrans.status","year": "$Year" },"weekStatus": [
                { $group: { _id: { status: "$Ctrans.status","week": "$Week" },count: { $sum: 1 } } }
            ]
        }
    }
])
本文链接:https://www.f2er.com/3083675.html

大家都在问