Reputation: 45941
Each document has a timestamp, so finding documents of a given age is straightforward.
How do find documents whose age in days % 3 == 0? It is trivial to do it in Ruby, but most of the documents won't be needed, so it would be better to find the relevant documents in Mongo.
Why?
The requirement is to send a reminder to users once every 3 days. I can schedule a task to run every day (or hour). One approach would be to run the task once every 3 days, but it would be better to send the reminder 3 days after they sign up, instead of 4-6 days after.
Also, this doesn't seem to be a very elegant approach. Is there a better way to take an action for documents once every 3 days?
Sinatra + Heroku + Mongo.
Upvotes: 1
Views: 81
Reputation: 3242
Assumption: you have the following documents with timestamp in your database.
> db.dinner.find()
{ "_id" : ObjectId("527d4edc6acba77bbdbcdbc5"), "timestamp" : 1383857393558, "dinner" : "strawberries" }
{ "_id" : ObjectId("527d4ee96acba77bbdbcdbc6"), "timestamp" : 1383770993558, "dinner" : "cherries" }
{ "_id" : ObjectId("527d4f116acba77bbdbcdbc7"), "timestamp" : 1383684593558, "dinner" : "blueberries" }
{ "_id" : ObjectId("527d4fa36acba77bbdbcdbc8"), "timestamp" : 1383943793558, "dinner" : "cranberries" }
>
Then you can find all documents that were authored 0,3,6,9, ... days ago with the following code:
today = new Date();
db.dinner.find().forEach(
function(entry) {
daysAgo = Math.floor((today.getTime() - entry.timestamp) / 1000 / 60 / 60 / 24);
if (daysAgo % 3 == 0) printjson(entry);
}
)
Upvotes: 2