鍍金池/ 問答/數(shù)據(jù)庫/ mongodb 如何 把數(shù)據(jù)分組,然后獲取分組里最大的那整條數(shù)據(jù)?

mongodb 如何 把數(shù)據(jù)分組,然后獲取分組里最大的那整條數(shù)據(jù)?

mongodb 如何 把數(shù)組分組,然后獲取分組里最大的那整條數(shù)據(jù)?

加入如下語句:


db.articles.aggregate( [
                        { $group: { _id: '$did', alld: { $max: '$time' } } }
                       ] );

我想 根據(jù)did字段分組,然后,分組內(nèi),獲取time最大的那條數(shù)據(jù)(是整條數(shù)據(jù))的所有字段,結(jié)果。而不是 _id 和alld 這兩個字段。

有什么辦法實現(xiàn)嗎??

例如:
{ "_id" : 1, "name" : "tom", "sex" : "男", "score" : 100, "age" : 34 }
{ "_id" : 2, "name" : "jeke", "sex" : "男", "score" : 90, "age" : 24 }
{ "_id" : 3, "name" : "kite", "sex" : "女", "score" : 40, "age" : 36 }
{ "_id" : 4, "name" : "herry", "sex" : "男", "score" : 90, "age" : 56 }
{ "_id" : 5, "name" : "marry", "sex" : "女", "score" : 70, "age" : 18 }
{ "_id" : 6, "name" : "john", "sex" : "男", "score" : 100, "age" : 31 }

根據(jù)sex 分組,然后獲取 改組score最高的那個人的所有字段。??mongodb到底如何實現(xiàn)的??

回答
編輯回答
硬扛

已經(jīng)有人問過了:mongodb分組查詢,取各班第1名

2018年6月6日 09:38
編輯回答
青檸
db.articles.aggregate(
   [
     { $sort: { score: -1} },
     {
       $group:
         {
           _id: "$sex",
           firstSalesDate: { $first: "$$ROOT" }
         }
     }
   ]
)
2017年2月7日 21:21