使用 mongodb/mongoid 排序时,有没有办法将所有 nil 值放在最后?
除了问题中已有的内容之外,确实没什么可说的。
使用 mongoid:
People.asc(:age)
我首先得到 nil 值。
有没有办法总是返回 nil last,或者告诉 mongodb 将 nil 视为非常高?
完全就像sql 中的相同问题的回答
Really not much more to tell than what is already in the question.
using mongoid:
People.asc(:age)
I get nil value first.
is there a way to always return nil last, or to tell mongodb to treat nil as very high?
Exactly like what is answered for the same problem in sql here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要非零年龄的升序,则不需要。如果这不重要,您可以看看是否
会将 nil 值放在末尾。或者,您可以尝试添加搜索参数以不返回 nil 值:
Not if you want ascending order for the non-nil ages. If that is unimportant, you could see if
will put the nil values at the end. Alternatively, you could try adding a search parameter to not return nil values:
我很确定 MongoDB 的答案是“不”。无法提供自定义排序功能,您只能提供用于排序的键。有对自定义排序功能的请求,他们甚至提到了您的特定用例:
所以你并不是唯一一个想在一端或另一端放置 null 的人。
我认为你现在能做的最好的事情就是用 Ruby 来做,就像这样:
我不使用 Mongoid,但大概
asc
给你一个 Enumerable,如果没有,那么也许你可以坚持一个 <代码>to_a在那里。当然,如果你正在分页,这种黑客行为是没有用的。I'm pretty sure the answer is "no" for MongoDB. There's no way to supply a custom sorting function, you can only supply the keys to sort on. There is a request for custom sorting functions and they even mention your particular use case:
So you're not alone in wanting to put
null
s at one end or the other.I think the best you can do right now is to do it in Ruby, something like this:
I don't use Mongoid but presumably
asc
gives you an Enumerable, if not then perhaps you could stick ato_a
in there. Of course this sort of hackery is useless if you're paginating.