I have a mongo store “task”, that has an array “answers”, which takes a hash, on of whose elements is a timestamp. So:
task ->
project_id,
answers ->
[
{
timestamp: <time>,
question_1: <answer_1>,
question_2: <answer_2>
},
{
timestamp: <time>,
question_1: <answer_1>,
question_2: <answer_2>
},
]
What I’d like to do is get a list of all tasks that have a given project ID, and whose latest answer timestamp field falls within the past 24h. The project ID thing is obviously pretty straightforward, and I can determine if a timestamp falls between the given period with $gte and $lt…but I don’t know how to scope that to the latest timestamp only.
I’m not using an ORM for this – so just the plain mongo query syntax preferred.
Any advice appreciated.
Map Reduce, as @shelman, mentioned is not required and I would not consider it the best method here. Note that MR is not really designed to run inline to your own application and is slow (by definition).
You would typically be better off with either the aggregation framework (which can easily do this) or better yet a normal query.
Now even though you want to know if the latest projects answers falls within 24 hours it is probably a good bet to assume that any project answer that falls within the 24 hour period should be included since that most likely means the latest does (if not then why not?). So this can be achieved with (again as @shelman said):
That will find any project with answers within the last 24 hours. You cna then filter out the first/last answer (which should always be the one your looking for) and bam, you have your result in a much more performant, inline to your application, manner