我正在尝试从MongoDB集合中获取“类型”字段的唯一值列表。以下示例文档:

{
       "_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"]

最好的方法是什么?希望我可以通过与Mongo查询而不是下载整个系列来做到这一点...

有帮助吗?

解决方案

在标准SQL DBMS上,这将通过以下查询完成:

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 }
            });

在这里,我要求数据库返回键“类型”(因此“ true”)的值,对于每个值,给定的降低函数将用于汇总找到的记录。在这里,我只是在更新每个记录的次数。如果您运行此查询,您会得到这样的东西:

[
    {
        "type" : "report",
        "count" : 5
    },
    {
        "type" : "memo",
        "count" : 15
    }
    {
        "type" : "research",
        "count" : 3
    }

]

您会注意到这不是订购的;甚至MongoDB文档也说,最简单的订购方法是进行客户端。

相关文档是 这里.

其他提示

您可以使用不同的: 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";
}

我不知道结果是否按频率排序。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top