【问题标题】:How to sort documents in mongodb so that null values appear last如何在mongodb中对文档进行排序,以使空值最后出现
【发布时间】:2019-02-26 00:12:41
【问题描述】:

假设我的 mongo 文档如下所示:

{
  _id: "some _id",
  name: "some name",
  type: "A" | "B" | "C" | or it may be null
}

当我调用db.getCollection('mycollection').find().sort({ type: -1 }) 时,我首先获取带有type: null 的文档,因为数据按规范类型排序,其中null 的规范值远低于数字/字符串的规范值

有没有办法形成一个查询,让空值最后出现?

我发现了这个问题How can I sort into that nulls are last ordered in mongodb?,但建议使用聚合并添加“假”值,这对我来说似乎不太好。

如果使用排序标准不为空的已排序文档和为空的文档形成分面,然后连接两个数组,则使用聚合可能会起作用,但当有多个排序标准时,这可能会变得复杂。

【问题讨论】:

  • 我尝试了类似你的场景,但是根据你的声明 null 具有比数字/字符串低得多的规范值。使用{type: 1} 排序首先返回nulls,而不是最后返回null 值。你想要哪种排序方式? null 是最后一个而不是 null 值在前,但不是倒序排列?
  • @PietroMartinelli 我希望null 的值始终保持不变
  • 使用 {test: -1} 排序(我忘记了前面评论中的减号)解决了这个问题,对我来说 - 以反向排序而不是 null 值的价格...

标签: mongodb aggregation-framework


【解决方案1】:

您可以使用 $type 运算符获取字段类型(nullstring),然后按字段类型加上 $sort,然后按您的字段,尝试:

db.col.aggregate([
    { $addFields: { fieldType: { $type: "$type" } } },
    { $sort: { fieldType: -1, type: 1 } },
    { $project: { "fieldType": 0 } }
])

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2021-12-24
    • 2017-04-30
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2018-03-06
    相关资源
    最近更新 更多