我怎样才能对 mongodb 中最后一次排序的空值进行排序? [英] How can I sort into that nulls are last ordered in mongodb?

查看:28
本文介绍了我怎样才能对 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}}
                 ]);

这篇关于我怎样才能对 mongodb 中最后一次排序的空值进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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