【问题标题】:Does an Index on Part of a MongoDB Query Offer Any Benefit?部分 MongoDB 查询的索引是否提供任何好处?
【发布时间】:2012-08-14 08:41:52
【问题描述】:

假设我在 MongoDB 中存储了具有以下结构的对象:

Transaction
{
  _id
  userId
  accountId
}

并假设我有以下索引:

db.Transaction.ensureIndex({"userId": 1})

以下查询是否利用索引来最小化搜索时间?

db.Transaction.find( {userId: 'user1234', accountId: 'account1234'} );

也就是说,MongoDB 是否使用索引来“缩减”userId 的结果,然后对accountId 进行表扫描?

db.Transaction.find( {userId: 'user1234', accountId: 'account1234'} ).explain()
{
    "cursor" : "BtreeCursor userId_1",
    "nscanned" : 2,
    "nscannedObjects" : 2,
    "n" : 1,
    "millis" : 1,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
            "userId" : [
                    [
                            "user1234",
                            "user1234"
                    ]
            ]
    }

查看查询的explain() 表示BtreeCursor userId_1,所以我认为它得到了user1234userId 的所有用户,然后扫描(仅有的两项)以找到@ 的accountId 987654332@ - 这是正确的吗?

提前致谢。

【问题讨论】:

    标签: mongodb indexing


    【解决方案1】:

    以下查询是否利用索引来最小化搜索时间?

    是的,确实如此。

    查看查询的 explain() 说 BtreeCursor userId_1,所以我假设它获取了所有用户 ID 为 user1234 的用户,然后扫描找到 account1234 的 accountId - 这是正确的吗?

    是的,你是对的。请参阅此处了解更多信息:

    【讨论】:

      猜你喜欢
      • 2014-04-02
      • 2013-01-17
      • 2019-02-10
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      相关资源
      最近更新 更多