2017-02-01 31 views
3

我看到以前的问题。但他们都不是基于最新的驱动程序。MongoDB PHP驱动程序:查询带有限制和跳过的不同记录

到目前为止,我的代码如下图所示:

$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017"); 
$regex1 = new MongoDB\BSON\Regex("^[A-z]","i"); 
$filter = ['searchcontent.name' => $regex1]; 
$options = [ 
    'limit' => 50, 
    'skip' => 0 
]; 

$query = new MongoDB\Driver\Query($filter, $options); 
$rows = $mongo->executeQuery('webdb.search', $query); 

foreach($rows as $r){  
    echo "<br/>".$r->searchcontent->name."<br/>"; 
} 

此代码返回的复印件,我重复在我的数据库。我想在这方面实现独特。我阅读官方文件,但无法找到任何东西。

我想是这样的:

$options = [ 
    'limit' => 50, 
    'skip' => 0, 
'distinct'=>'searchcontent.name' 
]; 

但它没有为我工作。请帮忙。

编辑:

PHP official documentation具有executeCommand明显的例子()。

但问题是我不能使用限制并跳过此代码。

摘要:

我想查询其中将包含limitskipdistinct

executeCommand()executeQuery()或其他任何东西将为我工作的解决方案。

回答

4

您可以使用聚合管道并将$group用于不同的记录。

$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017"); 
$regex1 = new MongoDB\BSON\Regex("^[A-z]","i"); 

$pipeline = [ 
    [ '$match' => ['searchcontent.name' => $regex1] ], 
    [ '$group' => ['_id' => '$searchcontent.name'] ], 
    [ '$limit' => 50 ], 
    [ '$skip' => 10 ], 
]; 

$aggregate = new \MongoDB\Driver\Command([ 
    'aggregate' => 'search', 
    'pipeline' => $pipeline 
]); 

$cursor = $mongo->executeCommand('webdb', $aggregate); 

foreach($cursor as $key => $document) { 
    var_dump($document); 
} 

另外,您应该通过composer提供类似的语法旧的API安装该库。

$collection = (new MongoDB\Client)->webdb->search; 

$cursor = $collection->aggregate([ 
    [ '$match' => ['searchcontent.name' => $regex1] ], 
    [ '$group' => ['_id' => '$searchcontent.name'] ], 
    [ '$limit' => 50 ], 
    [ '$skip' => 10 ], 
]); 

foreach($cursor as $key => $document) { 
    var_dump($document); 
} 
相关问题