如何在mongodb中对文档进行排序,以便最后显示空值

问题描述 投票:1回答:1

假设我的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?但是它建议使用聚合并添加“假”值,这对我来说似乎并不好。

如果使用排序文档形成一个facet,其中排序标准不为null,并且文档为null,然后将两个数组合并,则使用聚合可能会有效,但是当存在多个排序标准时,这可能会变得复杂。

mongodb aggregation-framework
1个回答
1
投票

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

db.col.aggregate([
    { $addFields: { fieldType: { $type: "$type" } } },
    { $sort: { fieldType: -1, type: 1 } },
    { $project: { "fieldType": 0 } }
])
© www.soinside.com 2019 - 2024. All rights reserved.