Created
October 9, 2014 09:40
-
-
Save ivan-kleshnin/6b17b0f6ac863cb17217 to your computer and use it in GitHub Desktop.
MongoDB: order positions by timedelta between CLOSE_DATE and NOW
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymongo import MongoClient | |
from bson import SON | |
from time import mktime | |
from datetime import datetime, timedelta | |
from time import mktime | |
from pprint import pprint | |
from random import randrange, randint, choice | |
def seed_position_times(db): | |
for position in db.positions.find(): | |
open_day = randrange( | |
mktime(now.timetuple()), | |
mktime(month_later.timetuple()) | |
) | |
close_day = randrange( | |
open_day, | |
open_day + randint(24*60*60, 24*60*60*3) | |
) | |
position['open_starts_on'] = datetime.fromtimestamp(open_day) | |
position['open_ends_on'] = datetime.fromtimestamp(close_day) | |
position['status'] = choice(['ok', 'closed']) | |
db.positions.save(position) | |
now = datetime.utcnow() | |
month_later = now + timedelta(days=30) | |
db = MongoClient().inshipping | |
# seed_position_times(db) | |
filters = { | |
'status': 'ok', | |
'open_starts_on': {'$gt': now} | |
} | |
result = db.positions.aggregate([ | |
{'$match': | |
filters | |
}, | |
{'$project': { | |
'timedelta': {'$subtract': ['$open_ends_on', now]}, | |
'open_starts_on': '$open_starts_on', | |
}}, | |
{'$sort': SON([ | |
('timeDelta', 1), | |
])}, | |
{'$project': { | |
'open_starts_on': '$open_starts_on', | |
}}, | |
]) | |
print(now) | |
print('---') | |
pprint([item['open_starts_on'] for item in result['result']][0:10]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment