0

I have 3 columns in the collection, they are '_id', 'value' and 'time'.

I've use below code get the id with max time

pipeline = [{'$group': {'_id': '$_id', 'time': {'$max': '$time'}}}]
values = list(db.fund_cost_log.aggregate(pipeline))

But I also want the value at the document with max time after group by id, how should I do it?

----- update ------

It's not duplicate with this, the answer of that one only gets the max time, I want the max time for each distinct id.

Community
  • 1
  • 1
Cuero
  • 1,169
  • 4
  • 21
  • 42
  • You probably just want a regular sort here instead of `.aggregate()`. `db.fund_cost_log.find({}).sort({ "time": -1 }).limit(1)`. It's a lot more efficient at what you seem to be trying to do here. – Neil Lunn Apr 07 '16 at 03:00
  • but yours only get the max time, I wants the max time for each distinct id. – Cuero Apr 07 '16 at 03:08
  • Umm. `_id` is "unique" per document. There is only one document per document. Or are you using new features of `$max` where `$time` is actually an array of values? Point is your `.aggregate()` does not actually appear to be doing anything. If you want "document boundaries" then you `$sort` first and use `$first` with `$group` for each field. And that is another "duplicate" question, so I'm not about to re-open this just to close it with another duplicate reference. – Neil Lunn Apr 07 '16 at 03:19
  • Also a duplicate of ["MongoDB - get documents with max attribute per group in a collection"](http://stackoverflow.com/a/25893214/2313887) – Neil Lunn Apr 07 '16 at 03:23
  • All right. I agree, the answer in this question solves my problem. Thank you. – Cuero Apr 07 '16 at 05:32

0 Answers0