Reputation: 2877
I have a query I run often where I use the Date to sort by. Basically I want to grab the next user due for some "processing" based on the last time they were processed, but I don't want to process users more often than every X minutes.
I have this query;
Users.findOne({'status':'active', 'lastCheck': {"$lt": sinceTime}).sort({"lastCheck": "ascending"}).exec(callback);
I know that for this to work I need to set lastCheck
as an index, but this is a Date
. Is it better to store that as a Number or Date?
Maybe there is a better way to do this altogether?
Thanks in advance
Upvotes: 0
Views: 652
Reputation: 16422
From here: "BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970).". So if you store it as millis you would not get any benefits really. I think it's better to store it as Date because you get all kinds of data integrity checks and conversions in your stack. Using $lt
is absolutely appropriate with dates.
As for the index you'll have to pick carefully. MongoDB can use only one index in the query condition. Here you are querying by 2 fields, so maybe a compound index would be better - depends on your data. Perhaps I would even create only 1 index on lastCheck
. You can use that same index in the sort
since you are sorting by that field. Mongo is able to use another index for sorting purposes.
Upvotes: 1