在 MongoDB 中最后对空值进行排序 [英] Sorting Null values last in MongoDB

查看:133
本文介绍了在 MongoDB 中最后对空值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下查询根据名为 sortIndex 的字段按升序填充来自 MongoDB 的项目.

I'm using the following query to populate items from MongoDB, in ascending order, according to a field called sortIndex.

有时虽然数据库中的项目没有 sortIndex 字段.通过以下查询,带有空 sortIndex 的项目显示在顶部,我想知道如何让它们显示在底部.为此我需要两个查询还是有办法使用一个查询?

Sometimes though items in the DB don't have the sortIndex field. With the following query, the items with a null sortIndex are showing up at the top, and I'm wondering how to get them to show up at the bottom. Would I need two queries for this or is there a way to use one query?

.populate({path: 'slides', options: { sort: { 'sortIndex': 'ascending' } } })

推荐答案

你可以这样做:

db.collection.aggregate([
    { $addFields: 
        { 
            hasValue : { $cond: [ { $eq: [ "$value", null ] }, 2, 1 ] },
        }
    },
])
.sort({hasValue : 1, value : 1});

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

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