mongodb php获取字段的唯一值
我试图从我的mongodb集合的'type'字段中获取唯一值的列表。mongodb php获取字段的唯一值
{
"_id" : ...,
"type" : "report",
"tasks" : ...
}
{
"_id" : ...,
"type" : "research",
"tasks" : ...
}
{
"_id" : ...,
"type" : "memo",
"tasks" : ...
}
{
"_id" : ...,
"type" : "memo",
"tasks" : ...
}
{
"_id" : ...,
"type" : "report",
"tasks" : ...
}
{
"_id" : ...,
"type" : "report",
"tasks" : ...
}
我在寻找,通过频率排序,独特的类型,可在文档的类型字段,那么:下面的示例文件
["report", "memo", "research"]
什么是做到这一点的最好办法?希望我能与蒙戈查询和不下载整个集合做到这一点...
在一个标准的SQL数据库管理系统,这将用下面的查询来完成:
SELECT type, count(*) as ct FROM table GROUP BY type ORDER BY ct;
有关MongoDB,这将使用组函数来完成,虽然这是稍微复杂些:
db.collection.group(
{key: { "type":true},
reduce: function(obj,prev) { prev.count += 1; },
initial: { count: 0 }
});
这里我要求db返回关键字“type”的值(因此为“true”),并且对于每个值,给定的reduce函数将用于汇总找到的记录。这里我只是更新每条记录出现次数。如果你运行这个查询,你会得到这样的东西:
[
{
"type" : "report",
"count" : 5
},
{
"type" : "memo",
"count" : 15
}
{
"type" : "research",
"count" : 3
}
]
你会注意到这是不是订购;即使是mongodb文档也会说,订购它的最简单方法就是在客户端进行。
相关文档是here。
您可以使用不同的:http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct
有一个在PHP文档的例子:http://php.net/manual/en/mongodb.command.php
$types = $db->command(array("distinct" => "yourCollection", "key" => "type"));
foreach ($types['values'] as $type) {
echo "$type\n";
}
我不知道结果是否按频率排序。
仍然需要一种方法来获取每个唯一值的频率,以便按频率对它们进行排序。我发现没有办法做到这一点使用独特的,因此与团体更轻松的解决方案。 – Roadmaster 2010-11-28 19:05:32
这个答案应该可以工作。只是一些额外的notes.This将是一个缓慢的查询,除非`type`索引。即使有索引,你也必须“走”整个索引。如果这是一个对时间敏感的查询,那么应该将它设置为map-reduce并按计划运行。 – 2010-11-28 19:49:09