在 Mongodb 中执行 $regex 查询时它是如何工作的?

How does it work when executing the $regex query in Mongodb?

我有一个关于 Mongodb 索引的问题。

据我所知,执行查询时,发现是在按选择的Index排序的数据中

db.HASH_TAG.find({"hashtag" : { $regex : "^Test"}}).sort({htseq:1}).hint("hashtag_1_htseq_1").explain("executionStats");

=========================解释=================== ============

executionStages  :{
  "stage" : "SORT", 
  "inputStage" : {
     "stage" : "SORT_KEY_GENERATOR",
     "inputStage" : {
             "stage" : "FETCH",
              "inputStage" : {
                        "stage" : "IXSCAN",
                        "indexName" : "hashtag_1_htseq_1", 
                         "keyPattern" : {
                            "hashtag" : 1.0, 
                            "htseq" : 1.0
                        }, 
                  }
          }
     }
}

请解释为什么SORT_KEY_GENERATOR出现在输入阶段。

您的正则表达式不是等式匹配,因此查询规划器无法提前保证索引 return 文档按排序顺序排列。

索引中的值将按主题标签排序,然后按 htseq 排序,正则表达式将匹配主题标签“Test”、“Tester”、“Tested”、“Testing”等,因此匹配的文档仍将需要按 htseq 个值的顺序 return 进行排序。

您可以像 { $regex : "^Test$"} 一样通过锚定正则表达式的两端来获得 index-supported 排序,但此时您也可以只使用相等匹配。