简体   繁体   English

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

[英]MongoDB PHP driver: Query for Distinct records with Limit and Skip

I saw previous questions on this. 我之前看过这个问题。 But none of them are based on latest driver. 但它们都不是基于最新的驱动程序。

So far my code is like below: 到目前为止,我的代码如下:

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

This code is returning duplicates as I have duplicates in my database. 此代码返回重复项,因为我在我的数据库中有重复项。 I want to implement distinct on this. 我想在此实施明确的。 I read official documentation, but not able to find anything. 我阅读官方文档,但无法找到任何内容。

I tried like this: 我试过这样的:

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

But it did not work for me. 但它对我不起作用。 Please help. 请帮忙。

Edit: 编辑:

PHP official documentation have a distinct example with executeCommand(). PHP官方文档有一个与executeCommand()有关的独特示例。

But the problem is I am not able to use limit and skip with this code. 但问题是我无法使用限制并跳过此代码。

Summary: 摘要:

I want a query which will contain limit , skip and distinct . 我想要一个包含limitskipdistinct的查询。

A solution with executeCommand() or with executeQuery() or anything else will work for me. 使用executeCommand()executeQuery()或其他任何东西的解决方案都适用于我。

You can use aggregation pipeline and use $group for distinct records. 您可以使用聚合管道并将$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);
}

Alternatively, you should install the library through composer which provides similar syntax as old api. 或者,您应该通过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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM