I've got a collection schema like this, the dates are posted in an human readable format but they are stored as ISO dates:
{
_id : ObjectId(...)
statuses :
[
{
status: "WIP",
date: 9/09/2015 09:31:16.205,
},
{
status: "Finished",
date: 9/09/2015 10:31:16.205,
}
]
}
I want to retrieve every collection document which it's most recent status (date
field) has the "Finished"
status set.
I was struggling how to do so in the lines ofdb.records.find({"statuses":{$elemMatch:{$max:date}}})
but I'm not able to accomplish the query properly as I don't realize how to compare then with the status
field.
It may only be possible with the aggregation framework, but I'm even more lost. I'd like some guidance with this kind of query.
EDIT: My issue has to do more with retrieving the max date in the statuses array and then look at that document status in the same query.
EDIT: After some attempts, this is my closest answer.
db.records.aggregate([{$match : {"statuses.status":"Finished"}},{$unwind : "$statuses"},{$sort: { "date": -1}},{$limit: 1}])