There are a few catches here.
When you use $group , the borders will be sorted in the order in which they were found, the initial or final stage of $sort . So, if your documents were originally in this order:
{ uid: 1, created: ISODate("2014-05-02..."), another_col : "x" }, { uid: 1, created: ISODate("2014-05-05..."), another_col : "y" }, { uid: 3, created: ISODate("2014-05-05..."), another_col : "w" }, { uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
Then just use $group without $sort at the end of the pipeline will return you the results as follows:
{ uid: 1, created: ISODate("2014-05-05..."), another_col : "y" }, { uid: 3, created: ISODate("2014-05-05..."), another_col : "w" }, { uid: 2, created: ISODate("2014-05-10..."), another_col : "z" },
This is one concept, but it really seems that you expect in the results, it requires returning the "last other fields" in the ordered uid order - this is what you are looking for. In this case, the way to get your result is first $sort , and then use $last :
db.mycollection.aggregate([
Or essentially apply sorting to what you want.
The difference between $last and $max is that the latter will select the "highest" value for this field in the _id group, regardless of the current sorting in unordered order. On the other hand, $last will select the value that occurs on the same "string" as the "last" grouping _id value.
If you really were looking for sorting array values, then the approach is similar. By storing the elements of the array in the "created" order, you also sort first:
db.mycollection.aggregate([
And documents with these fields will be added to the array with the order that they have already sorted.