MongoDB PHP驱动程序:使用限制和跳过查询不同的记录

Ari*_*jit 6 php mongodb

我之前看过这个问题.但它们都不是基于最新的驱动程序.

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

$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/>";
}
Run Code Online (Sandbox Code Playgroud)

此代码返回重复项,因为我在我的数据库中有重复项.我想在此实施明确的.我阅读官方文档,但无法找到任何内容.

我试过这样的:

$options = [
   'limit' => 50,
   'skip' => 0,
'distinct'=>'searchcontent.name'
];
Run Code Online (Sandbox Code Playgroud)

但它对我不起作用.请帮忙.

编辑:

PHP官方文档有一个与executeCommand()有关的独特示例.

但问题是我无法使用限制并跳过此代码.

摘要:

我想要一个包含的查询limit,skipdistinct.

使用executeCommand()或使用executeQuery()或其他任何方式的解决方案对我有用.

use*_*814 8

您可以使用聚合管道并$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);
}
Run Code Online (Sandbox Code Playgroud)

或者,您应该通过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);
}
Run Code Online (Sandbox Code Playgroud)