MongoDB-按不重复的字段进行汇总,然后每天进行计数

时间:2019-01-21 05:00:19

标签: mongodb pymongo aggregation

我有一个mongodb数据库,用于收集设备数据。 示例文档为

{
    "_id" : ObjectId("5c125a185dea1b0252c5352"),
    "time" : ISODate("2018-12-13T15:09:42.536Z"),
    "mac" : "10:06:21:3e:0a:ff",
}

目标是每天计算唯一的mac值,从数据库中的第一个文档到数据库中的最后一个文档。

我一直在玩耍,并得出结论,在聚合过程中,我将需要有多个小组和项目。

这就是我尝试过的-不知道它是朝着正确的方向还是完全搞砸了。

   pipeline = [
        {"$project": {
            "_id": 1,
            "mac": 1,
            "day": {
                "$dayOfMonth":"$time"
            },
            "month": {
                "$month":"$time"
            },
            "year": {
                "$year":"$time"
            }
        }
        },
        {
        "$project": {
            "_id": 1,
            "mac": 1,
            "time": {
                "$concat": [{
                    "$substr":["$year", 0, 4]
                },
                "-", {
                    "$substr": ["$month", 0, 2]

                },
                "-",
                {
                    "$substr":["$day", 0, 2]
                }]
                }
            }
        },
        {
            "$group": {
                "_id": {
                    "time": "$time",
                    "mac": "$mac"
                }
            },
            "$group": {
                "_id": "$_id.time",
                "count":{"$sum": 1},
            }
        }
    ]

    data = list(collection.aggregate(pipeline, allowDiskUse=True))

现在输出看起来没有进行任何聚合,

[{"_id": null, "count": 751050}]

我使用Pymongo作为驱动程序,并使用Mongodb 4。

理想情况下,它应该只显示日期和计数(例如{“ _id”:“ 2018-12-13”,“ count”:2}。

我希望获得一些反馈和建议。 预先感谢。

3 个答案:

答案 0 :(得分:3)

我更喜欢减少阶段数,尤其是避免不必要的$ group阶段。因此,我将使用以下管道进行操作:

Parent

答案 1 :(得分:1)

有一个名为“ $ dateToString”的运算符,它将解决您的大多数问题。

编辑:@Asya Kamsky没有仔细阅读问题,感谢您指出。这是新答案。

  pipeline = [
  {
    "$group": {
      "_id": {
        "date": {
          $dateToString: {
            format: "%Y-%m-%d",
            date: "$time"
          }
        },
        "mac": "$mac"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "count": {
        "$sum": 1
      }
    }
  }
]

答案 2 :(得分:0)

[
                {
            "$project": {
                "_id": 1,
                "mac": 1,
                "time": { "$dateToString": { "format": "%Y-%m-%d", "date": "$time", "timezone": "Africa/Johannesburg"}}
            },
        },

        {
            "$group": {
                "_id":{
                "time": "$time",
                "mac": "$mac",
            }}},{
            "$group": {
                "_id": "$_id.time",
                "count":{"$sum": 1}
            }},
         {"$sort": SON([("_id", -1)])}

]

确切地应该做什么。 谢谢。 :)

相关问题