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值放在末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-01 12:20