Mongodb复合索引 - 也是在_id排序中构建的?

时间:2017-09-28 09:23:47

标签: mongodb compound-index

我有一个复合索引

{ 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上创建另一个复合索引或创建?

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

1 个答案:

答案 0 :(得分:1)

您只是在userIDconnectionStatus上查询,因此您的复合索引不需要包含userTargetLastName。排序是在查询结果上完成的,并且它对于在排序字段上有索引不是必不可少的,因此在索引中包含_id并不重要。

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