问题
I want to find distinct records from a collected "pages".
I tried:
$Volume_numbers = Pages::find(array('fields'=>'DISTINCT volume_number'));
I also tried:
$params = array('conditions'=>array(
'distinct' => 'pages',
'key' => 'volume_number',
));
$pageVolumes = Pages::all($params);
as suggested in MongoDB documentation and also in one of the answers.
When I try to execute this through Mongo, I get correct results
> db.runCommand({distinct:'pages',key:'volume_number'})
{
"values" : [
22,
38
],
"stats" : {
"n" : 1084,
"nscanned" : 1084,
"nscannedObjects" : 1084,
"timems" : 25,
"cursor" : "BasicCursor"
},
"ok" : 1
}
回答1:
I don't believe there is a wrapper method in lithium\data\source\MongoDb
for the distinct
command; however, the MongoDb class does compose the PHP driver's Mongo and MongoDB classes, so you can do the following:
// Where $mongodb is an instance of lithium\data\source\MongoDb
$result = $mongodb->connection->command(array(
'distinct' => 'pages',
'key' => 'volume_number',
));
Alternatively, I'm sure Nate Abele would welcome a pull request to Lithium to add support for distinct
to the read()
method, just as it already has for group
(in fact, the current code makes a good starting point to implement this).
回答2:
This code worked for me!
$pageVolumes = Pages::connection()->connection->command(array(
'distinct' => 'pages',
'key' => 'volume_number',
));
Results:
Array
(
[values] => Array
(
[0] => 22
[1] => 38
)
[stats] => Array
(
[n] => 1084
[nscanned] => 1084
[nscannedObjects] => 1084
[timems] => 3
[cursor] => BasicCursor
)
[ok] => 1
)
来源:https://stackoverflow.com/questions/13310832/get-distinct-records-from-mongodb-using-lithium