带有$ in或$或的索引

时间:2016-03-01 13:33:05

标签: mongodb indexing

我的文档结构是这样的

{
    _id: "id1",
    field1: "val1",
    field2: "val2",
    outcome: "ABC"
}

我在结果字段上创建了索引。我必须找到仅包含{outcome:"ABC"}{outcome:"XYZ"}的所有文档。如果我使用$or$in,查询执行时间没有重大差异。例如

db.coll.find({$or:[{outcome:"ABC"},{outcome:"XYZ"}]}); 
db.coll.find({outcome:{$in:["ABC","XYZ"]}});

在这种情况下,我应该使用$or$in哪个运算符?为什么?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:2)

MongoDB docs

  

使用$or<expressions>对同一字段的值进行相等性检查时,请使用$in运算符代替$or运算符。

     

例如,要选择库存集合中数量字段值等于2050的所有凭证,请使用$in运算符:

db.inventory.find ( { quantity: { $in: [20, 50] } } )

因此,在您的情况下,最好使用

db.coll.find({outcome:{$in:["ABC","XYZ"]}});
相关问题