我该如何归类到null在mongodb中的最后排序? [英] How can I sort into that nulls are last ordered in mongodb?
本文介绍了我该如何归类到null在mongodb中的最后排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在mongo shell中执行了该查询
I excute this query in the mongo shell
db.getCollection('list').find({}).sort({next_time: 1})
结果是
next_time
--
null
null
null
2015-02-21 00:00:00
2015-03-25 00:00:00
2015-08-29 00:00:00
我希望得到这样的结果
next_time
--
2015-02-21 01:00:00
2015-03-25 01:00:00
2015-08-29 01:00:00
null
null
null
不同之处在于'null'在列表中的最后排序.我该怎么办?
The different is that 'null's are last ordered in the list. How can I do for this?
推荐答案
也许您可以使用聚合和人为的高端日期:
Perhaps you can use aggregation and an artificially high end date:
c = db.foo.aggregate([
{$project: {
next_time: 1,
nlt: { $ifNull: [ "$next_time", new ISODate("9000-01-01") ] }
}
}
,
{$sort: { "nlt": 1}}
]);
c.forEach(function(r) { printjson(r); });
或者,如果大多数材料都为空,而您根本不想处理这些文档,则将它们过滤掉,仅$sort
其余部分:
Alternatively, if the majority of the material has nulls and you don't want to deal with those docs at all, then filter them out and just $sort
the remainder:
db.foo.aggregate([
{$match: {"nt": {$exists: true}}}
,
{$sort: { "nt": 1}}
]);
这篇关于我该如何归类到null在mongodb中的最后排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文