用于排序的索引与聚合管道

Index vs Aggregation Pipeline for Sorting

我正在开发一个使用 MongoDB 作为其数据库的应用程序,并且为了对数据进行排序,我遇到了一个来自同事的有趣论点,即可以使用索引而不是聚合管道来获取排序数据。

我试过了,确实有效;使用具有指定字段和方向的索引在查询时对数据进行 return 排序。在使用聚合管道时,我也得到了相同的结果。

我创建了一个具有以下规范的索引:

index name: batch_deleted_a_desc

num: asc
marked: asc
value: desc

使用聚合管道:

> db.test.aggregate([{$match: {num:"3",marked:false}}, {$sort:{"value":-1}}])
{ "_id" : ObjectId("5d70b40ba7bebd3d7c135615"), "value" : 4, "marked" : false, "num" : "3" }
{ "_id" : ObjectId("5d70b414a7bebd3d7c135616"), "value" : 2, "marked" : false, "num" : "3" }
{ "_id" : ObjectId("5d70b3fea7bebd3d7c135614"), "value" : 1, "marked" : false, "num" : "3" }

使用索引:

> db.test.find({num:"3",marked:false})
{ "_id" : ObjectId("5d70b40ba7bebd3d7c135615"), "value" : 4, "marked" : false, "num" : "3" }
{ "_id" : ObjectId("5d70b414a7bebd3d7c135616"), "value" : 2, "marked" : false, "num" : "3" }
{ "_id" : ObjectId("5d70b3fea7bebd3d7c135614"), "value" : 1, "marked" : false, "num" : "3" }

如你所见,结果是一样的。但是我不确定使用索引来获取排序数据是一种好的做法,但是使用聚合管道(有时)比仅仅创建索引要花费更多的精力。

那么,哪个是最好的选择?

在问题的上下文中,更好的选择是聚合,因为它明确指定了排序

在查询示例中,结果按索引指定的顺序 return 编辑,因为查询正在使用索引 { num: 1, marked: 1, value: 1}。但是,查询中指定的任何内容都不能保证排序,这意味着结果可能会在将来的某个时候发生变化。例如,考虑要创建索引 { num: 1, marked: 1, updated_at: 1 } 的情况。查询规划器可能会决定改用此索引,这可能会导致结果顺序不同。

在没有排序的情况下,查询会 return 导致使用索引的顺序,但您不应在未明确指定的情况下依赖该顺序。引用 docs

Unless you specify the sort() method or use the $near operator, MongoDB does not guarantee the order of query results.