在mongoDB中持续排序无效值



我正在使用以下查询以升序顺序从mongodb中填充项目,该字段根据一个称为SortIndex的字段。

有时,尽管数据库中的项目没有SortIndex字段。有了以下查询,带有无效索引的项目在顶部出现,我想知道如何使它们显示在底部。我是否需要两个查询,或者有一种方法可以使用一个查询?

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

您可以做这样的事情:

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

重复:如何将零值保持在猫鼬的排序结束时?

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

不确定解决方案即将说。我无法对此进行测试,因为我现在没有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)
         }
      }
   ]
)

希望这会有所帮助!

最新更新