从集合中获取第n个项目 [英] Get nth item from a collection

查看:45
本文介绍了从集合中获取第n个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正处于mongodb的学习阶段.

I'm in the learning phase of mongodb.

我有一个测试网站项目,其中故事的每个步骤都是domain.com/step 例如,通过domain.com/14

I have a test website project where each step of a story is a domain.com/step for instance, step 14 is accessed through domain.com/14

换句话说,对于上述情况,我将需要访问集合中的第14个文档来提供它.

In other words, for the above case, I will need to access 14th document in my collection to serve it.

到目前为止,我一直在使用find().skip(n).limit(1)方法来返回第n个文档,但是当要跳过的文档太多时,它会变得非常慢.因此,我需要一种更有效的方式来获取收藏夹中的第n个文档.

I've been using find().skip(n).limit(1) method for this so far to return nth document however it becomes extremely slow when there are too many documents to skip. So I need a more efficient way to get the nth document in my collection.

任何想法都值得赞赏.

推荐答案

在您的文档中添加一个字段,告诉您它在哪一步,在该字段中添加索引并按其查询.

Add a field to your documents which tells you which step it is, add an index to that field and query by it.

文档:

{
     step:14
     text:"text",
     date:date,
     imageurl:"imageurl"
}

索引:

db.collection.createIndex({step:1});

查询:

db.collection.find({step:14});

依赖于集合中的自然顺序不仅缓慢(如您所知),而且也不可靠.当您开始一个新集合并插入一堆文档时,通常会按照插入它们的顺序查找它们.但是,当您在插入文档后更改文档时,可能会以无法预测的方式弄乱订单.因此,永远不要依赖插入顺序的一致性.

Relying on natural order in the collection is not just slow (as you found out), it is also unreliable. When you start a new collection and insert a bunch of documents, you will usually find them in the order you inserted them. But when you change documents after they were inserted, it can happen that the order gets messed up in unpredictable ways. So never rely on insertion order being consistent.

例外:上限​​集合确保插入顺序保持一致.但是很少有有用的用例,我认为您在这里没有这种用例.

Exception: Capped Collections guarantee that insertion order stays consistent. But there are very few use-cases where these are useful, and I don't think you have such a case here.

这篇关于从集合中获取第n个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆