Skip to content

Instantly share code, notes, and snippets.

@swinton
Last active October 9, 2015 19:25
Show Gist options
  • Save swinton/0fb086de306552e617ed to your computer and use it in GitHub Desktop.
Save swinton/0fb086de306552e617ed to your computer and use it in GitHub Desktop.

Notes

  • All the examples below assume the user's timezone is US/Central.

Basics

All activities from a device

Activity.objects(device="sausages")

All running activities from a device

Activity.objects(device="sausages", data__type="running")

All of today's activities so far from a device

Note:

  • end time strictly greater than start of today (in user's timezone)
today = arrow.now("US/Central").datetime.replace(hour=0, minute=0, second=0, microsecond=0)
Activity.objects(device="sausages", data__end_time__gt=today)

All of today's running activities so far from a device

today = arrow.now("US/Central").datetime.replace(hour=0, minute=0, second=0, microsecond=0)
Activity.objects(device="sausages", data__end_time__gt=today, data__type="running")

All of yesterday's running activities from a device

Notes:

  • start time strictly less than start of today (in user's timezone)
  • end time strictly greater than start of yesterday (in user's timezone)
today = arrow.now("US/Central").datetime.replace(hour=0, minute=0, second=0, microsecond=0)
yesterday = today - datetime.timedelta(days=1)
Activity.objects(device="sausages", data__start_time__lt=today, data__end_time__gt=yesterday, data__type="running")

Aggregation

Sum of all activities so far today

Notes:

  • need to drop down to pymongo to make use of the aggregation framework
today = arrow.now("US/Central").datetime.replace(hour=0, minute=0, second=0, microsecond=0)
Activity._get_collection().aggregate(
    [
        { "$match": { "device": "sausages", "data.end_time": { "$gt": today } } },
        { "$group": { "_id": "$data.type",  "total": { "$sum": "$data.duration" } } }
    ]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment