Mongodb php gets unique field values

I am trying to get a list of unique values โ€‹โ€‹from the 'type' field from my mongodb collection. Examples of 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 am looking for frequency-ordered unique types that are in the document type field, so:

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

What is the best way to do this? Hope I can do this by querying with mango and not downloading the whole collection ...

+3
source share
2 answers

In a standard SQL DBMS, this will be done with the following query:

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

on mongodb this would be done using a group function, although it is somewhat more complicated:

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

db "type" (, "true" ), . , . , - :

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

]

, ; mongodb docs , - .

.

+11

: http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

php doc : http://php.net/manual/en/mongodb.command.php

$types = $db->command(array("distinct" => "yourCollection", "key" => "type"));

foreach ($types['values'] as $type) {
    echo "$type\n";
}

, .

+1

Source: https://habr.com/ru/post/1777311/


All Articles