【问题标题】:Mongodb compound index - also built in _id sort?Mongodb复合索引 - 也内置_id排序?
【发布时间】:2018-03-09 23:37:47
【问题描述】:

我有一个复合索引

{ 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})

【问题讨论】:

    标签: mongodb compound-index


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我应该说我想将查询限制在 10 个。对于具有特定 connectionStatus 的用户 ID,可以说有 200 个结果。我想要 10 按 userTargetLastName 或 _id(或创建)排序。
    • 另外,感谢“explain()” - 我现在将使用它来检查事情是否按我的意愿工作
    • 您还可以使用 explain("executionStats") 和 explain("allPlansExecution") 来优化您的查询。见docs.mongodb.com/manual/reference/method/cursor.explain
    猜你喜欢
    • 1970-01-01
    • 2013-08-25
    • 2016-12-15
    • 2020-05-11
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多