Erimus Koo Erimus Koo - 1 year ago 105
Python Question

mongodb how to get max value of each "group with the same key"

I have a collection:


if I want the result is, the max value of 'updateTime' of the same 'name':


or finaly get a python dict:


How to do it most effective?

I do it now in python is:

for name in db.collection.distinct('name'):

is it do 'find' too many times?

Answer Source

you can do this in a single query with aggregation :


this will return

{ "_id" : "bob", "updateTime" : "2016-11-25" }
{ "_id" : "ada", "updateTime" : "2016-11-25" }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download