gpt4 book ai didi

php - 如何使用 mongodb 和 php 正确处理分页查询?

转载 作者:IT王子 更新时间:2023-10-29 00:07:53 28 4
gpt4 key购买 nike

我这样做对吗?我去看了一些带有 MySQL 的旧 PHP 代码,我已经设法让它工作,但是我想知道是否有更“干净”和“更快”的方法来完成这个。

首先我需要得到“文档”的总数

$total_documents = $collection->find(array("tags" => $tag, 
"seeking" => $this->session->userdata('gender'),
"gender" => $this->session->userdata('seeking')))->count();

$skip = (int)($docs_per_page * ($page - 1));
$limit = $docs_per_page;
$total_pages = ceil($total_documents / $limit);

//查询填充数组以便我可以分页显示

$data['result'] = $collection->find(array("tags" => $tag, 
"seeking" => $this->session->userdata('gender'),
"gender" => $this->session->userdata('seeking')))->limit($limit)->skip($skip)->sort(array("_id" => -1));

我的问题是,我可以一次性运行查询吗?我基本上运行了两次相同的查询,除了第二次我传递值以在记录之间跳过。

-- 新代码...

好吧,除非有人知道另一种方法来做到这一点(如果可能的话),否则我会说这是不可行的。话虽如此,我改变了通过 mongodb 运行查询的方式,这产生了更好看的代码。 ;-) 我试图尽量减少到数据库的行程,但是希望这不会影响性能。我的另一个尝试是计算数组中元素的数量,但很快发现这行不通,因为 $limit 和 $skip 参数会给出 ITS 文档总数。

$skip = (int)($docs_per_page * ($page - 1));
$limit = $docs_per_page;

$query = array("loc" => array('$near' => array('lat' => $latitude, 'lon' => $longitute) ),
"tags" => $tag, "seeking" => $this->session->userdata('gender'),
"gender" => $this->session->userdata('seeking'));

$fields = array("username", "zipcode", "tags", "birth_date");
$total_documents = $collection->find($query, array("_id"))->count();
$data['result'] = $collection->find($query, $fields)->limit($limit)->skip($skip);

最佳答案

由于 find()->limit()->skip() 的结果是 Mongo_Cursor,因此您不必执行两次实际查询。

以下应该也可以:

$skip = (int)($docs_per_page * ($page - 1));
$limit = $docs_per_page;

$query = array("loc" => array('$near' => array('lat' => $latitude, 'lon' => $longitute) ),
"tags" => $tag, "seeking" => $this->session->userdata('gender'),
"gender" => $this->session->userdata('seeking'));

$fields = array("username", "zipcode", "tags", "birth_date");
$cursor = $collection->find($query, $fields)->limit($limit)->skip($skip);
$total_documents = $cursor->count();
$data['result'] = $cursor;

顺便说一句,我首先误读了你的问题,我以为你不知道限制和跳过。

关于php - 如何使用 mongodb 和 php 正确处理分页查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3010744/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com