2016-11-25 104 views
1

我有一个集合:MongoDB中如何获得每个最大值“组具有相同键”

{'name':'ada','updateTime':'2016-11-25'} 
{'name':'bob','updateTime':'2016-11-25'} 
{'name':'ada','updateTime':'2016-11-20'} 
{'name':'bob','updateTime':'2016-11-20'} 
{'name':'ada','updateTime':'2016-11-15'} 
{'name':'bob','updateTime':'2016-11-15'} 
... 

,如果我想要的结果是,同样的“名字”的“更新时间”的最大值:

{'name':'ada','updateTime':'2016-11-25'} 
{'name':'bob','updateTime':'2016-11-25'} 
... 

或finaly获得Python字典:

{'ada':'2016-11-25','bob':'2016-11-25',...} 

如何做最有效?

我现在就做在python是:

for name in db.collection.distinct('name'): 
    result[name]=db.collection.find({'name':name}).sort('updateTime',-1)[0] 

是做 '找到' 过多少次?

回答

0

MongoDB中有与$最大运营商寻找最大价值的选择。

db.collection.aggregate([ 
    { 
     $group:{ 
     "_id":"$name", 
     updateTime:{ 
      $max:"$updateTime" 
     } 
     } 
    } 
]) 

以上查询在我的输出下面。

{ 
    "_id" : "bob", 
    "updateTime" : "2016-11-25" 
} 
{ 
    "_id" : "ada", 
    "updateTime" : "2016-11-25" 
} 
2

你可以用聚集做在一个单一的查询:

db.collection.aggregate([ 
    { 
     $sort:{ 
     updateTime:-1 
     } 
    }, 
    { 
     $group:{ 
     "_id":"$name", 
     updateTime:{ 
      $first:"$updateTime" 
     } 
     } 
    } 
]) 

这将返回

{ "_id" : "bob", "updateTime" : "2016-11-25" } 
{ "_id" : "ada", "updateTime" : "2016-11-25" } 
相关问题