在 MongoDB 中,当一个字段刚刚被测试其长度时,索引会有帮助吗?

In a MongoDB will an index help when a field is just being tested on its length?

我正在创建一个例程来检查中断处理并继续,在启动期间我正在执行以下搜索:

.find({"DocumentsPath": {$exists: true, $not: {$size: 0}}})

我希望它尽可能快,但是文档表明该索引用于在数据内扫描。我永远不需要在 "DocumentsPath" 中搜索,如果它在那里就使用它。创建索引似乎是我不想要的开销。然而,拥有索引可能会加快尺寸测试。

我的问题是这个字段是否应该在数据库中建立索引?

想发表评论,但这确实值得回答。这应该被索引吗?很可能,但出于其他目的。这在这里有区别吗?不,它没有。

要说明的重点是,在这种情况下,您的查询字词是多余的(或者可能更好)。我们来看例子:

{ "DocumentsPath": { "$exists": true } }

这将告诉您文档中是否确实存在与指定的 属性 匹配的元素。不,它不能使用索引。您可以使用 "sparse" 索引,甚至不需要调用它。

{ "DocumentsPath": { "$not": { "$size" : 0 } } }

这很可爱。是的,它测试数组的长度,但你在这里真正要问的是 "I don't want the array to be empty".

所以为了更好的解决方案。

  1. 使用 "sparse" 索引:

    db.collection.ensureIndex({ "DocumentsPath": 1 }, { "sparse": true })
    
  2. 查询索引的第零个元素

    { "DocumentsPath.0": { "$exists": true } }
    

仍然没有 "matching" 的索引,但至少 "sparse" 索引整理了一些我排除的文档和 "dot notation" form here is actually more efficient than evaluating via $size.