对 MongoDB 查询进行排序会导致返回的行数减少
我在 Mongoid(2.0.0.beta.17 和 2.0.2)/MongoDB 中排序时遇到问题。也许我对 MongoDB 的经验还不够,你们中的一些人可以帮助我理解我做错了什么?
用户级别的症状是:
- 查询未按日期或 ID 正确排序
- 用户帖子在看起来应该出现时却没有出现(这是类似 Twitter 的 园丁社交网站,最近的帖子有时不会显示)
irb(main):024:0> Update.all.size
=> 551
Update.ordered.size # (see below for definition)
=> 490
irb(main):010:0> Update.all.select{|u| u.created_at.nil?}
=> []
当我进入 mongo shell 并执行以下操作时:
var cursor = db.updates.find({}, {'_id': 1}).limit(600);
while (cursor.hasNext()) printjson(cursor.next());
我返回 454 行。
var cursor = db.updates.find({}, {'_id': 1}).sort({created_at : 1}).limit(600);
while (cursor.hasNext()) printjson(cursor.next());
还返回 454 行。
db.updates.find({}).sort({created_at: -1}).limit(1);
返回 2 月 23 日的更新。但我在 MongoDB 中有昨天的更新。 有什么想法吗?
我的模型是:
class Update
include Mongoid::Document
include Mongoid::Timestamps
include Paperclip
field :body
...
index [[ :created_at, Mongo::DESCENDING ]]
...
named_scope :ordered, :order_by => ([[:created_at, :desc]])
...
end
I'm having an issue with ordering in Mongoid (2.0.0.beta.17 and 2.0.2)/MongoDB. Perhaps I'm just not experienced enough with MongoDB, and some of you can help me understand what I'm doing wrong?
The user-level symptoms are:
- Queries not sorting correctly by date or ID
- User posts are not appearing when they seem like they should be (this is a Twitter-like social networking site for gardeners, and the most recent posts are sometimes not showing up)
irb(main):024:0> Update.all.size
=> 551
Update.ordered.size # (see below for definition)
=> 490
irb(main):010:0> Update.all.select{|u| u.created_at.nil?}
=> []
When I go into the mongo shell, and do:
var cursor = db.updates.find({}, {'_id': 1}).limit(600);
while (cursor.hasNext()) printjson(cursor.next());
I get 454 lines returned.
var cursor = db.updates.find({}, {'_id': 1}).sort({created_at : 1}).limit(600);
while (cursor.hasNext()) printjson(cursor.next());
Also returns 454 lines.
db.updates.find({}).sort({created_at: -1}).limit(1);
returns an update from February 23rd. But I have updates from yesterday in MongoDB.
Any ideas?
My model is:
class Update
include Mongoid::Document
include Mongoid::Timestamps
include Paperclip
field :body
...
index [[ :created_at, Mongo::DESCENDING ]]
...
named_scope :ordered, :order_by => ([[:created_at, :desc]])
...
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你能打印出
created_at
字段吗?您可能对保存日期字段的方式有疑问。输出是字符串吗? ISODate()?
Can you print out the
created_at
field?You may have an issue with how you're saving your date fields. Is the output there a string? an ISODate()?
我不明白为什么,但执行以下操作似乎可以解决问题:
named_scope :ordered, :order_by => ([[:created_at, :desc], [:_id, :desc]])
二次排序似乎有帮助。
其中第一个被排除在原始查询之外。
I didn't figure out WHY, but doing the following seems to fix the problem:
named_scope :ordered, :order_by => ([[:created_at, :desc], [:_id, :desc]])
It seems the secondary ordering helps.
The first of these was being left out of the original query.