我需要在集合中返回每个用户的最小client_timestamp值,但是我无法让$ min运算符以这种方式运行。有没有办法让查询返回集合中所有user_id的最小client_timestamp?
query = ??? db.collection.find(查询).distinct(" client_timestamp&#34)
示例文档结构:
{
"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"
}
答案 0 :(得分:1)
aggregation framework是您找到最小值的答案。它有$min
分组运算符,它在$group
管道阶段完成此操作:
db.collection.aggregate([
{ "$group": {
"_id": None,
"client_timestamp": { "$min": "$client_timestamp" }
}}
])
分组由_id
中指定的字段值的值或组合完成,其中任何Null或空值将对整个集合进行分组。
另请参阅文档中的SQL to Aggregation mapping chart以获取许多常见示例。