Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我认为在 MongoDB 中添加索引不会影响查询结果。但是,我遇到了一种发生这种情况的情况。
有一个名为 的集合scores。在没有索引的情况下,以下查询:
scores
db.scores.find({score: {$not: {$gt: 100}}})
返回值score不大于 100 的记录和score缺少键的记录。
score
但是,在字段上添加索引score会导致 MongoDB 排除score缺少键的记录。有没有办法防止这种情况?请注意,索引在我们的案例中是必不可少的。
当 MongoDB 使用索引时,它只在索引中查找结果。不幸的是,它的行为取决于它是完成完整的表扫描还是仅仅索引。
虽然有多种处理方法,但您可以执行以下操作:
db.scores.find({ $or : [ {score: { $exists: false }}, {score: {$not: {$gt: 100}}}]})
那只会检查任一条件是否为true. 如果您检查 的结果explain,您会发现它对这两个条件都使用了索引。
true
explain
虽然,如果您可以将其添加score到所有文档中,它可能会表现得更好,因为索引使用会更有效。