Get Distinct records from MongoDB using lithium

北慕城南 提交于 2020-01-06 04:16:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!