如何对 mongodb 中的文档进行排序以使空值出现在最后

Le *_*con 4 mongodb aggregation-framework

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

{
  _id: "some _id",
  name: "some name",
  type: "A" | "B" | "C" | or it may be null
}
Run Code Online (Sandbox Code Playgroud)

当我打电话时,db.getCollection('mycollection').find().sort({ type: -1 })我首先收到文档type: null,因为数据是按规范类型排序的,其中 null 的规范值比数字/字符串的规范值低得多

有没有办法形成查询,以便空值出现在最后?

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

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

mic*_*ckl 8

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

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