MongoDB:按现有字段排序,然后按字母顺序排序 [英] MongoDB: Sort by field existing and then alphabetically

查看:231
本文介绍了MongoDB:按现有字段排序,然后按字母顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,我有一个name字段.在某些记录中,它是一个空字符串,在其他记录中,它具有名称.

In my database I have a field of name. In some records it is an empty string, in others it has a name in it.

我正在查询中:

db.users.find({}).sort({'name': 1})

但是,这将首先返回带有空名称字段的结果,然后按字母顺序返回结果.正如预期的那样,执行.sort({'name': -1})会返回带有名称的结果,然后返回带有空字符串的结果,但是它是按字母顺序反向的.

However, this returns results with an empty name field first, then alphabetically returns results. As expected, doing .sort({'name': -1}) returns results with a name and then results with an empty string, but it's in reverse-alphabetical order.

是否存在一种优雅的方式来实现这种排序?

Is there an elegant way to achieve this type of sorting?

推荐答案

怎么样:

db.users.find({ "name": { "$exists": true } }).sort({'name': 1})

因为毕竟当您要排序的字段实际上不存在时,返回的值是null,因此其顺序比任何正结果都低".因此,如果您确实只是在寻找具有匹配值的东西,则排除那些结果是有意义的.

Because after all when a field you want to sort on is not actually present then the returned value is null and therefor "lower" in the order than any positive result. So it makes sense to exclude those results if you really are only looking for something with a matching value.

如果您真的想要所有结果并且不包含null内容,那么我建议您通过.aggregate()加权"它们:

If you really want all the results in there and regarless of a null content, then I suggest you "weight" them via .aggregate():

db.users.aggregate([
     { "$project": {
         "name": 1,
         "score": {
             "$cond": [
                 { "$ifNull": [ "$name", false ] },
                 1,
                 10
             ]
         }
     }},
     { "$sort": { "score": 1, "name": 1 } }
])

然后通过分配一个这样的值,将所有null结果移动到链的末端".

And that moves all null results to the "end of the chain" by assigning a value as such.

这篇关于MongoDB:按现有字段排序,然后按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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