在mongodb中计算不重复计数没有给出明显结果

时间:2018-11-21 11:48:19

标签: mongodb mongodb-query aggregation-framework

一个正努力解决no-sql的sql专家:

我正在mongodb中寻找类似

的查询的替代方法

select city, count(distinct device) from collection group by city, devicetype

我的收藏就像

{
"city":"city1",
"device": "device1"
"deviceType":1
},
{
"city":"city1",
"device": "device2"
"deviceType":0
},
{
"city":"city1",
"device": "device3"
"deviceType":1
},
{
"city":"city1",
"device": "device2"
"deviceType":0
}

分组后,我需要每个城市的devicetype使用的 distinct 设备

表示,输出将是

{
"city":"city1",
"deviceType":0,
"deviceCount":1     //device2
},
{
"city":"city1",
"deviceType":1,
"deviceCount":2     //device1, device3
}

我尝试过

"$group": {
                _id: { "city": "$city", "devicetype": "$devicetype" },
                "devicetype": { "$first": "$devicetype" },
                "count": { "$sum": 1 }
            }

我得到的是设备总数,而不是唯一的数量。

请提出建议!

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

db.collection.aggregate([
  { "$group": {
    _id: {
      "city": "$city",
      "deviceType": "$deviceType"
    },
    "deviceCount": { "$addToSet": "$device" },
    "count": { "$sum": 1 }
  }},
  { "$project": {
    "_id": 0,
    "city": "$_id.city",
    "deviceType": "$_id.deviceType",
    "deviceCount": { "$size": "$deviceCount" }
  }}
])

Output

[
  {
    "city": "city1",
    "deviceCount": 1,
    "deviceType": 0
  },
  {
    "city": "city1",
    "deviceCount": 2,
    "deviceType": 1
  }
]