【问题标题】:multiple group by query in mongodb aggregateMongoDB聚合中的多个分组查询
【发布时间】:2018-01-30 10:12:00
【问题描述】:

这是我文档的结构

{
"_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")
    );

【问题讨论】:

  • 还请包括您尝试过的尝试。
  • @Veeram 请检查我的编辑
  • 谢谢。预期输出是什么?
  • 它应该返回唯一MESSAGE_CONFIG_ID对应的唯一手机号码的计数。如果你能从我发布的 SQL 查询中理解的话

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


【解决方案1】:

您可以尝试以下聚合。

第一个 $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}
  }}
])

【讨论】:

  • 它返回的结果和我的一样 :(
  • 我已根据您的评论更新了答案。请立即尝试。
  • 你为什么要写另一个组??
  • 所以在第一组计数也将包括所有重复的行。所以第一组是获得不同的组合,第二组是计算 MESSAGE_CONFIG_ID 的手机号码。
  • 我也编辑并发布了我的 spring-data mongo 查询。我还没有执行,但你认为它会起作用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多