如何将$ setunion应用于此聚合?

时间:2019-07-15 10:44:45

标签: mongodb

Here my db is:

{
    "_id" : ObjectId("5d28667fb0adb622b905ccd2"),
    "requestedDate" : ISODate("2019-07-12T10:52:47.711Z"),
    "requestType" : "A",
    "isRequestSuccess" : false,
    "responseDate" : ISODate("2019-07-12T10:53:19.213Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5d28667fb0adb622b905ccd2"),
    "requestedDate" : ISODate("2019-07-12T10:52:47.711Z"),
    "requestType" : "C",
    "isRequestSuccess" : false,
    "responseDate" : ISODate("2019-07-12T10:53:19.213Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5d28667fb0adb622b905ccd2"),
    "requestedDate" : ISODate("2019-07-12T10:52:47.711Z"),
    "requestedType" : "A",
    "isRequestSuccess" : false,
    "responseDate" : ISODate("2019-07-12T10:53:19.213Z"),
    "__v" : 0
}

我需要通过每个requestType以及isRequestSuccess获取值:成功还是失败明智。

[
  { requestedType: "A", isRequestSuccess: 2, isRequestFalse: 1 },
  { requestedType: "C", isRequestSuccess: 1, isRequestFalse: 3 }
]

如何获取这些值?

1 个答案:

答案 0 :(得分:1)

db.getCollection('test').aggregate({
  "$group": {
      "_id": "$requestedType",
      "isRequestSuccess": {
          $sum: {
              $cond: ["$isRequestSuccess", 1, 0]
          }
      },
      "isRequestFalse": {
          $sum: {
              $cond: ["$isRequestSuccess", 0, 1]
          }
      }
  }
 })