我想基于 ValidationDate 返回过去30天和过去一年中mongodb集合中的文档总数。这是我的样本数据
{
"_id": {
"$oid": "570480d5d487dd2c577a4d5f"
},
"ValidationDate": {
"$date": "2016-04-05T22:00:03.335Z"
},
"DataRaw": " HF 13300100032016-03-30 23:40:05+0000+ 12.03+ 4.376+ 1387.00 0.0",
"ReadingsAreValid": true,
"locationID": " HF 133",
"Readings": {
"BatteryVoltage": {
"value": " 0.0"
},
"pH": {
"value": 4.376
},
"SensoreDate": {
"value": {
"$date": "2016-03-30T23:40:05.000Z"
}
},
"temperature": {
"value": 12.03
},
"Conductivity": {
"value": 1387
}
},
"HMAC": "0f38675cac8b3b761225c80b7441df36ddc4911ff30405835d7803dcde15d0b8"
}
这是我的代码
来自pymongo import Connection 来自datetime import datetime
def main():
conn = Connection()
db = conn.cloudtest
data = db.test_5_27
print data.find({"ReadingsAreValid":True}).count()
if __name__ == "__main__":
main()
代码返回集合中文档的总计数,但我想知道如何根据 ValidationDate
过去30天和过去一年对它们进行分组。答案 0 :(得分:1)
这样的事情:
import datetime
from pymongo import MongoClient
data = MongoClient().cloudtest.test_5_27
now = datetime.datetime.utcnow()
last_30d = now - datetime.timedelta(days=30)
last_year = now.replace(year=now.year - 1)
since_last_month = data.find({
"ReadingsAreValid": True,
"ValidationDate": {"$gte": last_30d}
}).count()
since_last_year = data.find({
"ReadingsAreValid": True,
"ValidationDate": {"$gte": last_year}
}).count()