From the docs, the distinct
command returns a list of distinct values for the given key across a collection. In this case you want to give it two parameters i.e. the key to use and the query which you want to pass in with the variable.
Consider the following example to demonstrate this
<?php
$m = new MongoClient("localhost");
$collection = $m->selectDB("test")->selectCollection("Data");
$collection->insert(array("filename" => "bar.txt", "name" => "bar"));
$collection->insert(array("filename" => "foo", "name" => "pippo"));
$collection->insert(array("filename" => "foo", "name" => "test"));
$retval = $collection->distinct("filename");
var_dump($retval);
$whereClause = array("name" => "pippo");
$retval = $collection->distinct("filename", $whereClause);
var_dump($retval);
?>
Another approach is using the command
method to issue the distinct
command. Consider the following mongo shell example which finds all the distinct values for the key "fieldname"
from all the documents in the "Data"
collection:
db.runCommand({ distinct: "Data", key: "filename" })
This returns a document with a field named values that contains the distinct filename
values:
{
"values": [ "foo", "bar", "abc", "def" ],
"stats": { ... },
"ok" : 1
}
The next example returns the distinct values for the field filename
from the "Data" collection with a query on documents whose name
field is equal to "pippo"
:
db.runCommand({ distinct: "Data", key: "filename", query: { name: "pippo"} })
which produces a similar document as above:
{
"values": [ "abc", "def" ],
"stats": { ... },
"ok" : 1
}
The equivalent PHP implementation with iteration follows:
<?php
...
$whereClause = array("name" => "pippo");
$filenames = $db->command(
array(
"distinct" => "Data",
"key" => "filename",
"query" => $whereClause
)
);
foreach ($filenames['values'] as $filename) {
$result1 = var_export($filename, true);
echo "value2: ".$result1;
$output[] = $result1;
echo "</br>";
}
?>