从集合中获取第n个项目

编程入门 行业动态 更新时间:2024-10-18 14:26:35
本文介绍了从集合中获取第n个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正处于mongodb的学习阶段.

I'm in the learning phase of mongodb.

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

I have a test website project where each step of a story is a domain/step for instance, step 14 is accessed through domain/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个项目

本文发布于:2023-11-29 12:40:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646421.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!