php - MongoDB PHP 驱动程序 : Query for Distinct records with Limit and Skip

标签 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/>";
}

此代码返回重复项,因为我的数据库中有重复项。我想对此实现不同的。我阅读了官方文档,但找不到任何东西。

我试过这样:

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

但这对我不起作用。请帮忙。

编辑:

PHP official documentation有一个与 executeCommand() 不同的例子。

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

总结:

我想要一个包含 limitskipdistinct 的查询。

带有 executeCommand() 或带有 executeQuery() 或其他任何东西的解决方案都对我有用。

最佳答案

您可以使用聚合管道并将 $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);
}

关于php - MongoDB PHP 驱动程序 : Query for Distinct records with Limit and Skip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41980806/

相关文章:

php - Activerecord 时区格式不正确

php - jQuery ajax 多行 "script"响应

javascript - 从 Meteor 中的 Mongodb 文档返回一个字段(一个数组)的内容

node.js - SailsJS - Mongo 查找与位置或条件关联(一对一)

mongodb - 使用MongoDB投影

javascript - node.js - 使用 arrayFilter 在 mongoose findOneandUpdate 中嵌套数组

javascript - 如何在express.js中编写查找和更新查询?

php - 如何将 laravel 查询生成器中的日期格式从 "2016-03-12"更改为 "12-Mar-2016"

php - 如果使用 yii2,Google Chrome 中的 Cookie 不会被删除

php - 在写字板中打开 csv 文件后,我不需要字段名称使用双引号