获取“上一个”带有 mongoId 的文档
我将 Images
存储在 mongoDB 中。它们按“created_at”排序。
现在,当我使用 Image.find("documentID")
加载单个项目时,我想根据 created_at
访问该文档之前的文档和之后的文档> 订单。
为此,我在 image.rb
中有两种方法和一个 default_scope:
default_scope asc(:created_at)
def previous_image
self.class.last(:conditions => {:created_at.lt => created_at})
end
def next_image
self.class.first(:conditions => {:created_at.gt => created_at})
end
mongoDB 中是否有本地方法来访问当前文档之前和之后的文档?
是否有更好的方法在 Rails 中使用 mongoID 创建此类命名范围来访问上一个和下一个项目,同时考虑性能(不要对一张图像查询三次)?
编辑:“previous_image”应该使用最后一个,而不是第一个。这解决了“跳过”项目的错误。不过,关于实现这一目标的正确方法的问题仍然存在。
I have Images
stored in mongoDB. They are sorted by "created_at".
Now, when I load a single item with Image.find("documentID")
I want to access the document just before and the one just after this one, based on the created_at
order.
For that, I have two methods and a default_scope in image.rb
:
default_scope asc(:created_at)
def previous_image
self.class.last(:conditions => {:created_at.lt => created_at})
end
def next_image
self.class.first(:conditions => {:created_at.gt => created_at})
end
Is there a native way in mongoDB to access the document before and after the current document?
Is there a better way to create such named scopes with mongoID in rails to access previous and next items, also considering performance (not querying three times for one image)?
Edit: The "previous_image" should use last, not first. That solves the bug of "skipping" items. The questions about the proper way to achive this remain, though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试这样的方法:
这种方法利用 Mongo id 的顺序。
You may try something like this:
This approach utilizes sequentiality of Mongo ids.
您可以根据 jhavdra 的响应尝试类似以下内容,但针对 Mongoid 语法进行了重写。
You could try something like the following, based on jhavdra's response, but rewritten for Mongoid syntax.