mongodb 聚合中的多个查询分组

multiple group by query in mongodb aggregate

这是我文档的结构

{
"_id" : "8113593870",
"_class" : "com.loylty.messagingEngine.entities.message.GroupIdDeliveryStatusReport",
"DATA_LIST" : [ 
    {
        "_id" : "8113593870-1",
        "mobile" : "7874671667",
        "status" : "DELIVRD",
        "senttime" : "2018-01-30 13:29:40",
        "dlrtime" : "2018-01-30 13:29:43",
        "custom" : "7874671667"
    }, 
    {
        "_id" : "8113593870-2",
        "mobile" : "7507829969",
        "status" : "DNDNUMB",
        "senttime" : "2018-01-30 13:29:40",
        "dlrtime" : "2018-01-30 13:29:40",
        "custom" : "7507829969"
    }
],
"CAMPAIGN_ID" : "5a70252612d91c7b085df083",
"MESSAGE_CONFIG_ID" : "5a702570f9dede4a357ffac4"

}

会有多个这种结构的文档

我想这样做

SQL: SELECT MESSAGE_CONFIG_ID,count(*) from GroupIdDeliveryStatusReport where CAMPAIGN_ID = '5a70252612d91c7b085df083' group BY DATA_LIST.mobile, MESSAGE_CONFIG_ID

如何在 mongo shell 和 spring-data 中做同样的事情。

我想要每个唯一 MESSAGE_CONFIG_ID DATA_LIST 中唯一手机号码的计数

这是我尝试过的方法,但没有达到预期效果。

db.getCollection('GROUP_ID_DELIVERY_STATUS').aggregate(
     {
        "$match" : {"CAMPAIGN_ID": "5a70252612d91c7b085df083" }
    },   
    { "$unwind" : "$DATA_LIST"},
    {
        "$match" : {"DATA_LIST.status": "DELIVRD" }
    },
    {
        $group: { _id: { mobile: '$DATA_LIST.mobile', MESSAGE_CONFIG_ID: '$MESSAGE_CONFIG_ID'},count: { $sum: 1 }  }

    }  

)

对于 spring-data 我试过这个

Aggregation aggregation = newAggregation(
            match(Criteria.where("CAMPAIGN_ID").in(campaignId)),
            unwind("DATA_LIST"),
            match(Criteria.where("DATA_LIST.status").is("DELIVRD")),
            group("DATA_LIST.mobile","MESSAGE_CONFIG_ID"),
            project("MESSAGE_CONFIG_ID","DATA_LIST.mobile")
    );

您可以尝试以下聚合。

第一个 $group 输出不同的值,然后第二个 $group 计算每个 "MESSAGE_CONFIG_ID" 的手机号码。

db.GROUP_ID_DELIVERY_STATUS.aggregate([
  {"$match":{"CAMPAIGN_ID":"5a70252612d91c7b085df083"}},
  {"$unwind":"$DATA_LIST"},
  {"$match" : {"DATA_LIST.status": "DELIVRD"}},
  {"$group":{
    "_id":{
      "mobile":"$DATA_LIST.mobile",
      "MESSAGE_CONFIG_ID":"$MESSAGE_CONFIG_ID"
    }
  }},
  {"$group":{
    "_id":"$_id.MESSAGE_CONFIG_ID",
    "mobilecount":{"$sum":1}
  }}
])