2014-09-10 34 views
1

我需要返回集合中每個用戶的最小client_timestamp值,但是我沒有能夠以這種方式獲得$ min操作符。有沒有辦法讓查詢返回集合中所有user_id的最小client_timestamp?返回一個集合中的ISODate值的最小值

query = ??? db.collection.find(查詢).distinct( 「client_timestamp」)

實例文檔結構:

{ 
    "device_type" : "Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz (8173 MB)", 
    "user_id" : "17204977745451858462", 
    "organization_id" : "1", 
    "client_timestamp" : "2014-09-10T04:46:39.201Z", 
    "client_session_id" : "PpfprJalFTNDZa2Ag1wUQ5D2Mfw", 
    "_id" : "0de1611e-d835-4557-9948-cbbf88afa098" 
} 

{ 
    "device_type" : "Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz (8173 MB)", 
    "user_id" : "17204977745451858462", 
    "organization_id" : "1", 
    "client_timestamp" : "2014-09-10T04:46:39.368Z", 
    "client_session_id" : "PpfprJalFTNDZa2Ag1wUQ5D2Mfw", 
    "_id" : "21e71acf-43e4-4a2d-b946-074fe7983034" 
} 

回答

1

aggregation framework是你尋找的最小值答案。它具有$min分組操作這不正是這一個$group流水線階段:

db.collection.aggregate([ 
    { "$group": { 
     "_id": None, 
     "client_timestamp": { "$min": "$client_timestamp" } 
    }} 
]) 

分組由_id,指定的字段值的值或組合進行,其中任何空或空值將集團的整個集合。

另請參閱文檔中的SQL to Aggregation mapping chart以瞭解許多常見示例。