0

I want to return the total number of documents in a mongodb collection for the last 30 days and last one year based on ValidationDate . Here is my sample data

{
    "_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"
}

Here is my code

from pymongo import Connection from 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()

The code returns the total count for documents in the collection but i will like to know how to group them according to last 30 days and last one year based on ValidationDate.

user1895915
  • 89
  • 11

1 Answers1

1

Something like this:

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()
A. Jesse Jiryu Davis
  • 22,038
  • 3
  • 48
  • 64