通过忽略数组中的重复项来计算文档

时间:2016-07-15 06:17:03

标签: mongodb mongodb-query nosql

每个约会都有一些服务。我想找到每项服务的总约会次数。

我的文档如下:

[{
  "appointmentTag":"xyz",
  "services" : [
    {
      "name" : "service1",
      "estimatedTime":20
    },
    {
      "name" : "service2",
      "estimatedTime":40
    }
  ]
},
{
  "appointmentTag":"abc",
  "services" : [
    {
      "name" : "service2",
      "estimatedTime":100
    },
    {
      "name" : "service2",
      "estimatedTime":30
    }
  ]
}

预期输出如下:

{"serviceName":"service1", "count":1}
{"serviceName":"service2", "count":2}

我尝试的查询:

db.appointments.aggregate([
    {"$unwind": "$services"},
    {"$group": {
        "_id": "$services.name",
        "count": {"$sum":1}
    }}
]);

获得以下结果:

{"serviceName":"service1", "count":1}
{"serviceName":"service2", "count":3}

1 个答案:

答案 0 :(得分:3)

你几乎是正确的。展开后,当您按serviceName分组而不是计数时,请使用appointmentTag的$ addToSet,然后计算该数组。像这样:

   db.test.aggregate([
  {
    "$unwind": "$services"
  },
  {
    "$group": {
      "_id": "$services.name",
      "appointments": {
        "$addToSet": "$appointmentTag"
      }
    }
  },
  {
    "$project": {
      "ServiceName": "$_id","_id":0,
      "countOfAppointments": {
        "$size": "$appointments"
      }
    }
  }
])