2014-09-10 40 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以了解许多常见示例。