Mongo Aggregate-获取多个值在查询结果中出现的次数

时间:2019-05-05 14:51:59

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我正在尝试计算两个单独的字段为真的次数。我有两个值“ clickedWouldRecommend”和“ clickedWouldNotRecommend”。这些值也默认为FALSE。在界面中单击按钮时,它们设置为TRUE。我正在尝试查看每个branch.name有多少clickedWouldRecommend = true和有多少clickedWouldNotRecommend = true。

db.appointments.aggregate([
{
  $match: {
    $and: [
      {
        'branch.org_id': '100000'
      },
      { "analytics.clickedWouldRecommend": true },
      // Add OR statement to include analytics.clickedWouldNotRecommend = true?
    ]
  }
},
{
  $group: {
    _id: '$branch.name',
    wouldRecommend: { $sum: 1 }
  }
}
])

这提供的结果类似于:

 {
  "_id": [ 'Clinic Name' ],
   "wouldRecommend": 115.0
 }

我需要修改查询以查找analytics.clickedWouldNotRecommend设置为true的情况。我正在尝试获得与此类似的输出(还请注意,如果可能,从_id中删除数组):

 {
  "name": 'Clinic Name'
   "wouldRecommend": 115,
   "wouldNotRecommend": 10
 },
 {
  "name": 'Second Clinic Name'
   "wouldRecommend": 200,
   "wouldNotRecommend": 12
 }

这是截断的模型/模式:

      {
  branch: [
    {
      name: {
        type: String,
        required: true
      },
      clinic_id: {
        type: String,
        required: true
      },
      org_id: {
        type: String
      }
    }
  ],
  analytics: {
    clickedWouldRecommend: {
      type: Boolean,
      default: false
    },
    clickedWouldNotRecommend: {
      type: Boolean,
      default: false
    }
  },
  date: {
    type: Date,
    default: Date.now
  }
};

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

db.appointments.aggregate([
  { "$match": { "branch.org_id": "100000" }},
  { "$unwind": "$branch" },
  { "$facet": {
    "wouldRecommend": [
      { "$match": { "analytics.clickedWouldRecommend": true }},
      { "$group": { "_id": "$branch.name" }}
    ],
    "wouldNotRecommend": [
      { "$match": { "analytics.clickedWouldNotRecommend": true }},
      { "$group": { "_id": "$branch.name" }}
    ]
  }}
])

db.appointments.aggregate([
  { "$match": { "branch.org_id": "100000" }},
  { "$unwind": "$branch" },
  { "$group": {
    "_id": "$branch.name",
    "wouldRecommend": {
      "$sum": {
        "$cond": [{ "$eq": ["$analytics.clickedWouldRecommend", true] }, 1, 0]
      }
    },
    "wouldNotRecommend": {
      "$sum": {
        "$cond": [{ "$eq": ["$analytics.clickedWouldRecommend", true]}, 1, 0]
      }
    }
  }}
])