Imagine we have the following set of documents stored in mongodb:
{ \"fooId\" : \"1\", \"status\" : \"A\", \"timestamp\" : ISODate(\"2016-01-01T00:00:00.000Z
Though there is no direct way to bring back original documents and I don't see any value, but try following aggregation query:
db.collection.aggregate([
{$sort: {fooId:1, timestamp: -1}},
{$group:{_id:"$fooId", doc:{$first:"$$ROOT"}}},
{$project:{_id:0, doc:["$doc"]}}
]).forEach(function(item){
printjson(item.doc[0]);
});
This query will emit:
{
"_id" : ObjectId("570e76d5e94e6584078f02c4"),
"fooId" : "2",
"status" : "B",
"timestamp" : ISODate("2016-01-02T00:00:00.000+0000"),
"otherInfo" : "BAR"
}
{
"_id" : ObjectId("570e76d5e94e6584078f02c8"),
"fooId" : "3",
"status" : "D",
"timestamp" : ISODate("2016-01-04T00:00:00.000+0000"),
"otherInfo" : "BAR"
}
{
"_id" : ObjectId("570e76d5e94e6584078f02c2"),
"fooId" : "1",
"status" : "C",
"timestamp" : ISODate("2016-01-03T00:00:00.000+0000"),
"otherInfo" : "BAR"
}