mongodb - Mongo - 复合索引与前缀的约束

标签 mongodb

From the Mongo docs:

If you have a collection that has both a compound index and an index on its prefix (e.g. { a: 1, b: 1 } and { a: 1 }), if neither index has a sparse or unique constraint, then you can remove the index on the prefix (e.g. { a: 1 }). MongoDB will use the compound index in all of the situations that it would have used the prefix index.

约束如何产生影响?

最佳答案

最好通过矛盾的例子来解释这一点。

1) 假设您有一个稀疏复合索引 {a, b} 和一个常规索引 {a},然后是文档

{ a : null, foo : "bar" }

不会成为稀疏索引的一部分,但会在常规 {a} 索引中建立索引。因此,使用稀疏索引无法找到带有 { a : null } 的文档,但可以使用常规索引找到它们(作为旁注,如果存在许多这样的文档,树就会变得不平衡而且很慢)。

2) 假设您有一个复合 {a, b} 索引和一个唯一 {a} 索引,那么以下两个文档将违反唯一约束{a} 索引,但不是复合索引,即使您将其转换为唯一索引也是如此:

{ a : 1, b : 1 }
{ a : 1, b : 2 }  // the {a,b} tuple is different, but a isn't unique

因此,唯一的a 索引的存在与否决定了第二个文档是否可以插入。

3) 同样,{a, b} 元组的唯一性并不意味着 a 本身的唯一性,等等。您可以找到所有组合的矛盾,除非两个索引既不稀疏也不具有唯一约束。

关于mongodb - Mongo - 复合索引与前缀的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29555457/

相关文章:

c# - C# 中的 MongoDB 地理空间索引

node.js - 如何使用 mongodb 查询从深度集合中删除文档?

node.js - 在 Mongoose 中设置查找后转换 Hook 的最简单方法

collections - MongoDB一次查询多个集合

node.js - 设置 GrapqQL 日期格式

ruby-on-rails - 返回查询中的嵌入文档

mongodb - 在 mongodb 中处理批量插入失败

linux - 在 linux shell 中运行 MongoDB 命令的错误替换

java - spring 数据 mongodb 存储库保存

mongodb - 以mongo方式设计