MongoDB多條件分組聚合查詢


 
         

1、樣例數據

{
    "_id" : ObjectId("5fa13fb76c3107345a82c047"),
    "_class" : "java.util.HashMap",
    "date" : "2020-11-03",
    "result" : "命中失敗",
    "activityCode" : "TEST_CODE_123",
    "activityName" : "測試活動123",
    "channel" : "大唐"
}
{
    "_id" : ObjectId("5fa13fb76c3107345a82c049"),
    "_class" : "java.util.HashMap",
    "date" : "2020-11-03",
    "result" : "命中失敗",
    "activityCode" : "TEST_CODE_456",
    "activityName" : "測試活動456",
    "channel" : "大漢"
}
{
    "_id" : ObjectId("5fa13fb76c3107345a82c050"),
    "_class" : "java.util.HashMap",
    "date" : "2020-11-03",
    "result" : "命中失敗",
    "activityCode" : "TEST_CODE_456",
    "activityName" : "測試活動456",
    "channel" : "大秦"
}

 

2、需求分析

需要統計某一日期下不同活動不同渠道的調用量

3、統計SQL

db.collectionName.aggregate([{
    $match: {
        "date": "2020-11-03",
        "result": "命中失敗"
    }
},
{
    $group: {
        _id: {
            activityCode: "$activityCode",
            channel: "$channel"
        },
        activityCode: {
            "$first": "$activityCode"
        },
        channel: {
            "$first": "$channel"
        },
        total: {
        $sum: 1
        }
    }
},
{
    $project: {
        _id: 0
    }
}])

4、SQL說明

#MongoDB的聚合管道將MongoDB文檔在一個管道處理完畢后將結果傳遞給下一個管道處理
db.COLLECTION_NAME.aggregate({管道操作1},{管道操作2},...)

#這里其實就兩個問題:如何多條件分組、如何展示各個分組條件的列
#多條件分組寫法
{$group:{_id:{"別名1":"$分組字段1","別名2":"$分組字段2",····},total:{$sum:1}}}

#展示各個分組條件的列
#如果不經過處理直接查詢會得到如下值:
{
  "_id" : {
    "activityCode" : "TEST_CODE_123",
    "channel" : "大唐"
  },
  "total" : 1
}
#這里activityCode、channel就會被包裹在_id里面,需要手工處理
#取出_id里分組字段對應的值寫法
{ $group: { _id: { activityCode: "$activityCode", channel: "$channel" }, activityCode: { "$first": "$activityCode" }, channel: { "$first": "$channel" }, total: { $sum: 1 } } }
#說明:
   $first:根據資源文檔的排序獲取第一個文檔數據  別名1:{"$first": "$分組字段1"}、別名2:{"$first": "$分組字段2"}
或者$last:根據資源文檔的排序獲取最后一個文檔數據 別名1:{"$last": "$分組字段1"}、 別名2:{"$last": "$分組字段2"}
#得到結果
{
  "_id" : {
    "activityCode" : "TEST_CODE_123",
    "channel" : "大唐"
  },
  "activityCode" : "TEST_CODE_123",
  "channel" : "大唐",
  "total" : 1
}
#最后在 $project: { _id: 0} 配置_id隱藏輸出,得到想要的結果:
{
  "activityCode" : "TEST_CODE_123",
  "channel" : "大唐",
  "total" : 1
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM