mongodb php获取字段唯一值 [英] mongodb php getting fields unique values

查看:76
本文介绍了mongodb php获取字段唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从mongodb集合的'type'字段中获取唯一值的列表.以下示例文件:

I'm trying to get a list of unique values from the 'type' field from my mongodb collection. Example documents below:

{
       "_id" : ...,
       "type" : "report",
       "tasks" : ...
}
{
       "_id" : ...,
       "type" : "research",
       "tasks" : ...
}
{
       "_id" : ...,
       "type" : "memo",
       "tasks" : ...
}
{
       "_id" : ...,
       "type" : "memo",
       "tasks" : ...
}
{
       "_id" : ...,
       "type" : "report",
       "tasks" : ...
}
{
       "_id" : ...,
       "type" : "report",
       "tasks" : ...
}

我正在寻找按频率排序的文档类型字段中的唯一类型,所以:

I'm looking for, ordered by frequency, the unique types that are in the type field of the documents, so:

["report", "memo", "research"]

执行此操作的最佳方法是什么?希望我可以通过查询mongo而不下载整个集合来做到这一点...

What's the best way to do this? Hopefully I can do this by querying with mongo and not downloading the entire collection...

推荐答案

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

On a standard SQL DBMS this would be done with the following query:

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

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

on mongodb this would be done using the group function, although it's slightly more complicated:

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

在这里,我要求数据库返回键"type"的值(因此为"true"),对于每个值,给定的reduce函数将用于汇总找到的记录.在这里,我只是更新每条记录出现多少次的计数.如果运行此查询,您将得到类似以下内容的信息:

Here I'm asking the db to return values for the key "type" (hence the "true"), and for each value, the given reduce function will be used to aggregate the found records. Here I'm just updating a count of how many times each record appears. If you run this query you'll get something like this:

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

]

您会发现这不是命令的;甚至mongodb文档都说,最简单的订购方法是在客户端进行.

You'll notice this is not ordered; even the mongodb docs say that the easiest way to order it is to do it client-side.

相关文档位于此处.

这篇关于mongodb php获取字段唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆