1

我有一个复合索引

{ userID:1, connectionStatus: 1, userTargetLastName: 1})

我想支持两个查询:

UserConnection.find( { $and : [ { userID : req.decoded.id }, { connectionStatus : 'accepted' } ] })
                .sort({'_id': -1}).exec()

UserConnection.find( { $and : [ { userID : req.decoded.id }, { connectionStatus : 'accepted' } ] })
                .sort({'userTargetLastName': 1}).exec()

我很困惑是否需要第二个复合索引来按 _id 排序,或者它是否“内置”到我的复合索引中?(根据 mongodb 文档,我的复合索引还应该支持 userID:1、connectionStatus:1 查询(但我可以按什么顺序对它们进行排序?按 _id ?)。所以我需要在 _id 或 created 上添加另一个复合索引?

 { userID:1, connectionStatus: 1, created: -1})
4

1 回答 1

1

您只查询userIDand connectionStatus,因此您的复合索引不需要包含userTargetLastName。排序是根据查询的结果完成的,并且在排序字段上具有索引不是必需的,因此包含_id在索引中并不重要。

检查索引使用的最佳方法是在explain()查询中使用该函数。这将告诉您很多关于正在使用哪个索引,以及它的效率如何(扫描的文档数量等)。

于 2017-09-28T11:07:00.633 回答