mongodb php getting fields unique values
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:
开发者_JAVA百科["report", "memo", "research"]
What's the best way to do this? Hopefully I can do this by querying with mongo and not downloading the entire collection...
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;
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 }
});
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
}
]
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.
Relevant documentation is here.
You can use distinct : http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct
There is an example in the 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";
}
I don't know if the results are ordered by frequency.
精彩评论