【发布时间】:2017-06-22 08:44:31
【问题描述】:
我在数据库中的记录如下:
{
"_id" : ObjectId("592d4f43d69b643ac0cb9149"),
"timestamp" : "2017-03-01 17:09:00",
"Technique-Meteo_Direction moyenne du vent_Mean value wind direction[]" : 0.0,
"Technique-Meteo_Précipitations_Precipitation status[]" : 0.0,
"Technique-Meteo_Direction du vent_Wind direction[]" : 0.0
}
{
"_id" : ObjectId("592d3a6cd69b643ac0cae395"),
"timestamp" : "2017-01-30 09:31:00",
"Technique-Electrique_Prises de Courant_Power1[W]" : 14.0,
"Technique-Electrique_Eclairage_Power2[W]" : 360.0,
"Technique-Electrique_Electroménager_Power3[W]" : 0.0,
"Technique-Electrique_VMC Aldes_Power4[W]" : 14.0,
"Technique-Electrique_VMC Unelvent_Power5[W]" : 8.0
我的时间戳是一个简单的字符串,由于其他算法的更改量很大,我不想碰它。 但是,我想做一些普通的操作。实际上,其他字段是带有测量值的传感器名称。我每分钟有一个记录,我想在一小时、一天或一个月内平均这些值。
就在之前,我创建了一个查询来计算一个字段每月现有值的数量
countExistingPerMonth = client[page1.currentDB][page2.currentColl].find({"$and":[{"timestamp":{"$regex": regexExpression}}, {chosenSensor:{"$exists": True}}]}, temp_doc).count()
我使用 $regex 表达式来查找与所选月份匹配的文档。
有没有什么办法可以使用这种方法进行我的平均操作?
我试图做一些事情(下)。我也尝试使用正则表达式进行聚合,但这是不可能的。
self.sensorsStats = []
for chosenSensor in self.chosenSensors:
countPerMonth = []
years = []
incre_year = int(page5.combo_startYear.get())
if (incre_year<=int(page5.combo_endYear.get())):
while(incre_year!=(int(page5.combo_endYear.get())+1)):
years.append(str(incre_year))
incre_year += 1
for year in years:
for month in ["01","02","03","04","05","06","07","08","09","10","11","12"]:
regexExpression = '^'+year+'-'+month+'-..'
test = client[page1.currentDB][page2.currentColl].aggregate([{"$match":{"timestamp":{"$regex": regexExpression}}}, {"$group":{"_id":chosenSensor, "average":{"$avg":{chosenSensor}}}}])
【问题讨论】:
标签: python mongodb aggregation-framework pymongo