Search code examples
mongodbfinddistinctlithium

Get Distinct records from MongoDB using lithium


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
}

Solution

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