3

我正在尝试从我的 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 查询而不是下载整个集合来做到这一点......

4

2 回答 2

11

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

SELECT type, count(*) as ct FROM table GROUP BY type ORDER BY ct;

在 mongodb 上,这将使用 group 函数完成,尽管它稍微复杂一些:

db.collection.group(
           {key: { "type":true},
            reduce: function(obj,prev) { prev.count += 1; },
            initial: { count: 0 }
            });

在这里,我要求数据库返回键“type”的值(因此为“true”),并且对于每个值,给定的 reduce 函数将用于聚合找到的记录。在这里,我只是更新每条记录出现的次数。如果您运行此查询,您将得到如下信息:

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

]

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

相关文档在这里

于 2010-11-28T18:49:09.927 回答
1

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

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

于 2010-11-28T18:47:24.937 回答