在mongodb聚合中通过查询多个组

时间:2018-01-30 10:12:01

标签: mongodb mongodb-query aggregation-framework spring-data-mongodb mongo-shell

这是我的文件的结构

{
"_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:从GroupIdDeliveryStatusReport中选择MESSAGE_CONFIG_ID,count(*)   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")
    );

1 个答案:

答案 0 :(得分:0)

您可以尝试以下聚合。

首先$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}
  }}
])