php mongodb在集合中找到第n个条目 [英] php mongodb find nth entry in collection
本文介绍了php mongodb在集合中找到第n个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检索收藏夹中的第n个条目.
这似乎在使用find()
时有效,但我认为使用findOne()
甚至sort()
有更清洁的解决方案?
任何人都可以帮忙写出更好的方式写这个
I am trying to retrieve the nth entry in my collection.
This seems to work using find()
but i would think there is a cleaner solution using findOne()
and maybe sort()
?
can anyone help out with a better way of writing this please
$mongo = new Mongo();
$db = $mongo->mydb;
$collection = $db->user;
$cursor = $collection->find();
$i=0;
foreach ($cursor as $obj){
if ($i==3)
echo $obj["_id"];//echo's the 3rd entry id
$i++;
}
此处提供的解决方案不适用我的问题,这就是为什么我问这个问题.
The solution provided here is not applicable to my problem, which is why I'm asking this question.
推荐答案
使用上面的代码中的(n-1)跳过:
Use skip of (n-1), from your code above:
$cursor = $collection->find();
$cursor->skip(3);
$cursor->next();
$doc = $cursor->current();
但是我认为最好的方法可能是在文档中保留一个可用作索引的计数器.
But I think probably the best way is to keep a counter in your document that you can use as an index.
这篇关于php mongodb在集合中找到第n个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文