Reputation: 3517
Having some trouble issuing a simple query from the PHP Mongo driver. This is the shell query:
db.testing.distinct('summary.type').sort();
According to the documentation, I can do a db->command
to use the distinct query. Here is what I've tried:
$all_types = $db->command(
array(
"distinct" => "summary.type",
"key" => "summary.type"
)
);
var_dump($all_types);
But rather than getting back the data I expect, I only get a cursor with indexes like stats
, nscanned
and nscannedObjects
What am I doing wrong?
Thanks, ns
Upvotes: 0
Views: 3059
Reputation: 6922
The result you're looking for is actually in the values
key of the command's response. If you look at the entire output of var_dump()
, you'll see keys for values
, stats
(which you referred to), and ok
.
On the JavaScript console, the collection's distinct()
helper function actually handles the unwrapping for you, which you can see when viewing the source:
> db.testing.distinct
function (keyString, query) {
var res = this._distinct(keyString, query);
if (!res.ok) {
throw "distinct failed: " + tojson(res);
}
return res.values;
}
Also, I believe you have an error in the command being issued through the PHP driver. The distinct
option should refer to the collection name, and key
should refer to the field name. See the Distinct docs for more information on that.
Upvotes: 1
Reputation: 36784
Commands don't return a MongoCursor object, but always just one document. Just like with findOne()
. In this returned document, the values
array element in the returned array contains an array of all your results:
<?php
$m = new Mongo; $c = $m->demo->pubs; $c->drop();
$c->insert( array( 'name' => 'Betsy Smith', 'city' => 'London' ) );
$c->insert( array( 'name' => 'London Tavern', 'city' => 'London' ) );
$c->insert( array( 'name' => 'Lammars', 'city' => 'Manchester' ) );
$c->insert( array( 'name' => 'Weatherspoons', 'city' => 'Coventry' ) );
$r = $m->demo->command( array(
'distinct' => 'pubs',
'key' => 'city',
'query' => array( 'name' => array( '$ne' => 'Weatherspoons' ) )
) );
var_dump( $r['values'] );
?>
Which returns:
array(2) {
[0] =>
string(6) "London"
[1] =>
string(10) "Manchester"
}
Upvotes: 1