使用mongodb/mongoid排序时,是否可以将所有nil值放在末尾? [英] Is there a way to put all the nil value at the end when sorting with mongodb/mongoid?

查看:210
本文介绍了使用mongodb/mongoid排序时,是否可以将所有nil值放在末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要说的真的不多于问题中已经存在的内容.

Really not much more to tell than what is already in the question.

使用蒙古型:

People.asc(:age)

我先得到nil值.
是否有办法始终返回nil last ,或告诉mongodb将nil视为非常高?

I get nil value first.
is there a way to always return nil last, or to tell mongodb to treat nil as very high?

所遇到的问题完全相同这里

推荐答案

我很确定MongoDB的答案是否".无法提供自定义排序功能,只能提供要进行排序的键. 对自定义排序功能的请求,它们甚至提到您的特定用例:

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:

用于自定义排序/索引的javascript排序助手
[...]
可以将其用于按字母顺序对字段进行排序,然后将具有空值的文档放在结果集的末尾吗?
[...]
@nick-是

javascript sort helper for custom sorting / indexing
[...]
Could this be used to sort alphabetically on a field, and put documents with a null value at the end of the result set?
[...]
@nick - yes

因此,您并不是一个人只想将null放在一端或另一端.

So you're not alone in wanting to put nulls at one end or the other.

我认为您现在可以做的最好的就是在Ruby中进行操作,如下所示:

I think the best you can do right now is to do it in Ruby, something like this:

nils, not_nils = People.asc(:age).partition { |p| p.age.nil? }
people = not_nils + nils

我不使用Mongoid,但是asc大概可以给你一个Enumerable,如果没有的话,也许您可​​以在其中插入to_a.当然,如果您要分页,这种黑客手段就没用了.

I don't use Mongoid but presumably asc gives you an Enumerable, if not then perhaps you could stick a to_a in there. Of course this sort of hackery is useless if you're paginating.

这篇关于使用mongodb/mongoid排序时,是否可以将所有nil值放在末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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