1

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
}
Nilam Doctor
  • 491
  • 7
  • 18
  • 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 )` – Nilam Doctor Nov 09 '12 at 20:03

2 Answers2

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).

jmikola
  • 6,892
  • 1
  • 31
  • 61
  • I added: use lithium\data\source\MongoDb; and $result = $mongodb->connection->command(array( 'distinct' => 'pages', 'key' => 'volume_number', )); To the code.. no results. – Nilam Doctor Nov 09 '12 at 18:34
  • If there were no results, then `$mongodb` wasn't the same database resource used for the Pages model in your application. Based on your comment above, it looks like `Pages::connection()` returned the reference you needed. – jmikola Nov 09 '12 at 22:18
0

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
)
Pang
  • 9,564
  • 146
  • 81
  • 122
Nilam Doctor
  • 491
  • 7
  • 18