Mar*_*ark 3 php querying mongodb mongodb-php
我正试图从我的mongodb集合中的'type'字段中获取一个唯一值列表.以下示例文档:
{
"_id" : ...,
"type" : "report",
"tasks" : ...
}
{
"_id" : ...,
"type" : "research",
"tasks" : ...
}
{
"_id" : ...,
"type" : "memo",
"tasks" : ...
}
{
"_id" : ...,
"type" : "memo",
"tasks" : ...
}
{
"_id" : ...,
"type" : "report",
"tasks" : ...
}
{
"_id" : ...,
"type" : "report",
"tasks" : ...
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找按频率排序的文档类型字段中的唯一类型,因此:
["report", "memo", "research"]
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?希望我可以通过查询mongo而不是下载整个集合来做到这一点......
Roa*_*ter 11
在标准SQL DBMS上,这将使用以下查询完成:
SELECT type, count(*) as ct FROM table GROUP BY type ORDER BY ct;
Run Code Online (Sandbox Code Playgroud)
在mongodb上,这将使用group函数完成,尽管它稍微复杂一些:
db.collection.group(
{key: { "type":true},
reduce: function(obj,prev) { prev.count += 1; },
initial: { count: 0 }
});
Run Code Online (Sandbox Code Playgroud)
这里我要求db返回键"type"的值(因此为"true"),对于每个值,给定的reduce函数将用于聚合找到的记录.在这里,我只是更新每条记录出现次数的计数.如果你运行这个查询,你会得到这样的东西:
[
{
"type" : "report",
"count" : 5
},
{
"type" : "memo",
"count" : 15
}
{
"type" : "research",
"count" : 3
}
]
Run Code Online (Sandbox Code Playgroud)
你会发现这不是订购的; 即使是mongodb文档说最简单的订购方式是在客户端进行.
相关文档在这里.
| 归档时间: |
|
| 查看次数: |
6082 次 |
| 最近记录: |