I'm trying to find documents in a collection, ordered by their date. This works, but I get the documents with null
in the date field at the bottom, I want these first.
我想在一个集合中找到文件,按日期排序。这是可行的,但是我在底部的日期字段中获得了null的文档,我首先需要这些。
MyModel.find({ }, null, { sort: { date: -1 } }, function(err, models) {
// Models sorted with the "largest" date first and models with null dates last
});
If I change the sorting to { date: 1 }
I do get the documents with null
at first, but the order otherwise is reverse, which I do not want.
如果我将排序更改为{date: 1},我首先确实获得了具有null的文档,但是顺序相反,这是我不希望看到的。
How can I achieve the desired behaviour?
我怎样才能达到理想的行为?
1 个解决方案
#1
4
Unfortunately it appears there's no trivial way to do this, akin to SQL's "nulls first" / "nulls last" syntax. This feature is mentioned in this Mongo bug:
不幸的是,似乎没有简单的方法可以做到这一点,类似于SQL的“nulls first”/“nulls last”语法。这个特性在Mongo bug中提到:
https://jira.mongodb.org/browse/SERVER-153
https://jira.mongodb.org/browse/server - 153
Where it's looped in with the larger feature of custom sorting functions. (I really wish this were broken out into a separate feature request because I would think implementing only the nulls first/last bit should be much easier than custom sorting functions and still provide a lot of value.)
它与自定义排序函数的更大特性相关联。(我真的希望将它分解成一个单独的特性请求,因为我认为只实现null first/last位应该比自定义排序函数容易得多,并且仍然提供很多价值。)
Anyway, the work-around for the time being is to just query separately for the null values in addition to your existing query:
不管怎样,目前的解决方法是除了现有查询之外,单独查询空值:
How are null values in a MongoDB index sorted?
MongoDB索引中的空值如何排序?
MyModel.find({ date: null });
MyModel.find({ date: { $ne: null } }).sort({ date: -1 } });
#1
4
Unfortunately it appears there's no trivial way to do this, akin to SQL's "nulls first" / "nulls last" syntax. This feature is mentioned in this Mongo bug:
不幸的是,似乎没有简单的方法可以做到这一点,类似于SQL的“nulls first”/“nulls last”语法。这个特性在Mongo bug中提到:
https://jira.mongodb.org/browse/SERVER-153
https://jira.mongodb.org/browse/server - 153
Where it's looped in with the larger feature of custom sorting functions. (I really wish this were broken out into a separate feature request because I would think implementing only the nulls first/last bit should be much easier than custom sorting functions and still provide a lot of value.)
它与自定义排序函数的更大特性相关联。(我真的希望将它分解成一个单独的特性请求,因为我认为只实现null first/last位应该比自定义排序函数容易得多,并且仍然提供很多价值。)
Anyway, the work-around for the time being is to just query separately for the null values in addition to your existing query:
不管怎样,目前的解决方法是除了现有查询之外,单独查询空值:
How are null values in a MongoDB index sorted?
MongoDB索引中的空值如何排序?
MyModel.find({ date: null });
MyModel.find({ date: { $ne: null } }).sort({ date: -1 } });