mongo多重计数和偏差结果

时间:2018-10-20 17:34:08

标签: mongodb mongodb-query aggregation-framework aggregate

我有一个mongodb集合,如下所示:

[

  {
      "_id" : ObjectId("5ba0e5a99e7537012371855a"),
      "user_id" : 2,
      "action" : 0,
      "source" : 1,
      "service" : "FootPlus",
      "free" : false,
      "source_detail" : {
          "source_type" : "landing",
          "source_id" : 2,
          "promoter_id" : 1
      },
      "created_at" : ISODate("2018-09-18T11:46:49.000Z")
  }

  {
      "_id" : ObjectId("5ba0e5cc9e7537013d57e37a"),
      "user_id" : 2,
      "action" : 1,
      "service" : "FootPlus",
      "source" : 0,
      "created_at" : ISODate("2018-09-18T11:47:24.000Z"),
      "source_detail" : {
          "source_type" : "landing",
          "source_id" : 2,
          "promoter_id" : 1
      }
  }
]

我想按source_detail.promoter_id分组并计数action = 0和action = 1 并将每个启动子的作用计数= 0除以作用计数= 1 所以我的结果应该是:

[
    {
        "promoter_id": 2
        "action_0": 27,
        "action_1": 9,
        "devide": 3
    },
    {
        "promoter_id": 3
        "action_0": 18,
        "action_1": 3,
        "devide": 6
    }
]

我怎么能达到这个结果? 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总。

类似

db.colname.aggregate([
 {"$group":{
  "_id":"$source_detail.promoter_id",
  "action_0":{"$sum":{"$cond":[{"$eq":["$action",0]},1,0]}},
  "action_1":{"$sum":{"$cond":[{"$eq":["$action",1]},1,0]}}
 }},
 {"$addFields":{"divide":{"$divide":["$action_0","$action_1"]}}}
])