我这样做对吗?我go 看了一些使用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运行查询的方式,从而生成了外观更好的代码.;-)我想尽量减少go DB的次数,但希望这不会影响性能.我的另一个try 是计算数组中的元素数,但很快发现,自从$limit&amp$skip参数将给出它的文档总数.

$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);

推荐答案

Since the result of find()->limit()->skip() is a Mongo_Cursor you don't have to execute the actual query twice.

以下几点也应该起作用:

$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;

顺便说一句,我第一次误读了你的问题,我以为你不知道极限&;跳过

Mongodb相关问答推荐

MongoDB $lookup 查找字段值数组

在 ExpirePolicy 之后从 Store 中删除元素

DB.collection('comments').find() 不工作

根据条件删除一些数组元素并将数组的大小更新为mongo中的另一个文件

$lookup 的参数必须是字符串

如何修改 mongodb 中嵌套对象数组中的字段名称/键?

MongoDB乘以对象值?

Mongodb:查询嵌套在数组中的json对象

字段类型在 MongoDB 索引中是否重要?

如果我在 MongoDB 上使用 LINQ,为什么会失go 性能?

在 MongoDB 中合并两个集合

如何为 node.js 中的 MongoDB 索引指定 javascript 对象中的属性顺序?

何时使用Singleton单例、Transient和使用 Ninject 和 MongoDB 的请求

Mongoose 为所有嵌套对象添加 _id

Spring Data MongoDB - 在哪里以编程方式为 Mongo 集合创建索引?

如何在 Mongoid 中引用嵌入的文档?

用于 MongoDB 的 Node.js 模块

将日期从毫秒转换为 ISODate 对象

MissingSchemaError:Schema hasn't been registered for model

有没有办法防止 MongoDB 向集合名称添加复数形式?