Query by date range and aggregation in pymongo

1,128 views
Skip to first unread message

SivaSankara Reddy Bommireddy

unread,
Jul 17, 2015, 12:40:59 AM7/17/15
to mongod...@googlegroups.com
I am trying to get documents by date range and then aggregate on those documents. Right now, I am trying the following to achieve that.

import datetime,time
import pymongo
from bson.son import SON

con1 = pymongo.MongoClient("myHost",27017)
db = con.myDB
posix_time1 = time.mktime(datetime.datetime(2015, 07, 14, 0, 0, 0).timetuple())
posix_time2 = time.mktime(datetime.datetime(2015, 07, 15, 0, 0, 0).timetuple())

pipeline = [
{"$match":{"time":{"$gte":int(posix_time1),"$lt":int(posix_time2)}}},
{"$unwind":"$foo1"},
{"$group":{"_id":"$foo1.boo","sum1":{"$sum":"$foo1.boo1"}}},
{"$sort":SON([("sum1",-1)])}
]
print(list(db.myColl.aggregate(pipeline)))

But, the result is an empty list. My guess is the problem with the dates I am passing. Please point me towards better solution.

Thank You!

Rhys Campbell

unread,
Jul 17, 2015, 2:47:12 AM7/17/15
to mongod...@googlegroups.com
Hello,

Ideally we'd have an example document.

Rhys

Bernie Hackett

unread,
Jul 17, 2015, 11:23:15 AM7/17/15
to mongod...@googlegroups.com, ssr...@gmail.com
Assuming you stored BSON datetimes (represented by python datetime.datetime) instead of you own integer representation, use python datetime.datetime in your match expression.

{"time":{"$gte": datetime.datetime(2015, 07, 14, 0, 0, 0),"$lt": datetime.datetime(2015, 07, 15, 0, 0, 0)}}
Reply all
Reply to author
Forward
0 new messages