我这样做了吗?我去看了一些旧的PHP代码和MySQL,我设法让它工作,但我想知道是否有一个更"清洁"和"更快"的方式来实现这一点.
首先,我需要获得"文件"的总数
$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);
wimvds.. 22
由于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;
顺便说一下我误读了你的问题,我以为你不知道限制和跳过.
由于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;
顺便说一下我误读了你的问题,我以为你不知道限制和跳过.