首页 > 解决方案 > mongodb - 嵌入式字段与嵌入式文档索引

问题描述

所以我想知道如果我要在文档上创建索引,它是否也会固有地在嵌入字段上创建索引?

所以对于这个例子:

{
  name: {
          first: "Yukihiro",
          last: "Matsumoto"
        }
}

如果它是嵌入式文档索引,将执行搜索:

   {
     "name.first": "Yukihiro",
     "name.last": "Matsumoto"
   }

导致它使用索引进行搜索,还是会查找文档 O(n)?

标签: mongodbindexing

解决方案


是的,只要文档不大于允许的索引大小 - https://docs.mongodb.com/manual/core/index-single/#create-an-index-on-embedded-document

您可以通过查询上的“解释”功能检查特定查询是否正在使用索引。表示它已使用"stage": "IXSCAN"索引。

"winningPlan" : {
        "stage" : "FETCH",
        "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                        "type" : 1
                },
                "indexName" : "type_1",
                "isMultiKey" : false,
                "isUnique" : false,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 1,
                "direction" : "forward",
                "indexBounds" : {
                        "type" : [
                                "[\"teacher\", \"teacher\"]"
                        ]
                }
        }
}

推荐阅读