【问题标题】:Sorting Null values last in MongoDB在 MongoDB 中对 Null 值进行最后排序
【发布时间】:2017-04-30 11:49:30
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript mongodb


【解决方案1】:

重复:How to keep null values at the end of sorting in Mongoose?

无论如何发布相同的解决方案...

我不确定我要说的解决方案。我无法测试这一点,因为我现在没有设置 mongo db,但我认为您可以使用 <collection>.aggregate 以及 $project$sort 来实现这一点。

示例代码:

db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            description: { $ifNull: [ "$amount", -1*(<mimimum value>)* ] }
         }
      },
      { 
         $sort : { 
           amount : (-1 or 1 depending on the order you want)
         }
      }
   ]
)

希望这会有所帮助!!

【讨论】:

    【解决方案2】:

    你可以这样做:

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

    【讨论】:

    • 点评来源: 您好,请不要只回答源代码。尝试对您的解决方案如何工作提供一个很好的描述。请参阅:How do I write a good answer?。谢谢
    猜你喜欢
    • 2021-12-24
    • 2021-12-11
    • 2013-07-12
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 2015-08-14
    • 2020-05-23
    • 2020-11-18
    相关资源
    最近更新 更多