You can use the $max grouping function in the Aggregate structure to find the last document for each group_id . You will need additional requests to obtain complete documents based on grouped criteria.
var results = new Array(); db.groups.aggregate( // Find documents with latest date for each group_id { $group: { _id: '$group_id', date: { $max: '$date' }, }}, // Rename _id to group_id, so can use as find criteria { $project: { _id: 0, group_id:'$_id', date: '$date' }} ).result.forEach(function(match) { // Find matching documents per group and push onto results array results.push(db.groups.findOne(match)); });
Examples of results:
{ "_id" : ObjectId("5096cfb8c24a6fd1a8b68551"), "group_id" : 1, "date" : ISODate("2012-11-03T00:00:00Z"), "foo" : "bar" } { "_id" : ObjectId("5096cfccc24a6fd1a8b68552"), "group_id" : 2, "date" : ISODate("2012-11-01T00:00:00Z"), "foo" : "baz" } { "_id" : ObjectId("5096cfddc24a6fd1a8b68553"), "group_id" : 3, "date" : ISODate("2012-11-03T00:00:00Z"), "foo" : "bat" }
Stennie
source share