1

玩过之后

db.largecollection.find( { $or : [ { identifierX : "sha1_hash123" } , { identifierY : "md5_hash456" } , { identifierZ : "another_hash789" } ] } )

我检查了 mongodb 自动准备的索引。除了标识符 x/y/z 的“单个”ensureIndex 之外,现在还有一个标识符 X_1_identifierY_1_identifierZ_1 并且性能下降:-(

您是否有想法或提示如何向 mongodb 解释使用单个标识符的索引更快,因为我没有 $and,但是 $or 查询?

谢谢

4

1 回答 1

3

MongoDB 不会自行创建索引。这是应用程序、用户或框架所做的事情。对于您的查询,MongoDB 只能使用 identifierX、identifierY 或 identifierZ 的索引。但是,如果您没有这样的索引,那么当然不会使用任何索引。该identifierX_1_identifierY_1_identifierZ_1索引不能用于此查询。

在这种情况下,您可能需要为所有这些标识符创建一个索引:

db.ensureIndex( { 'identifierX' : 1 } );
db.ensureIndex( { 'identifierY' : 1 } );
db.ensureIndex( { 'identifierZ' : 1 } );

MongoDB 一次只能使用一个索引,它会尝试选择“最好的”一个。尝试使用explain来查看正在选择哪个索引:

db.largecollection.find( { $or : [
    { identifierX : "sha1_hash123" },
    { identifierY : "md5_hash456" },
    { identifierZ : "another_hash789" }
] } ).explain();

这应该会给你一些关于正在使用哪个索引的想法。

There is an exception for $or though, where MongoDB can use a different index for each of the parts and de-dup for you. It's here in the docs. It would (of course) still not use the compound index, and you need the indexes that I've written here above.

于 2012-06-05T12:42:42.813 回答