MongoDB - 索引为$或,$ exists:false和排序查询

时间:2016-03-28 06:49:04

标签: mongodb indexing

假设我有以下文件:

{
    "_id": ObjectId('56f8c8ac1e80d48f16000007'),
    "a": 1,
    "b": 2,
    "c": {
        "c1": 31,
        "c2": 32
    },
    "d": 4,
    "e": 5
}

其中c2并不总是存在。

除了$or字段上的$exists: false'c.c2'字段上的sorting之外,我还需要使用e运算符进行查询。

这是查询的样子:

db.test.find({
    $or : [
      {
        'a': 1,
        'b': 2,
        'c.c1': 31,
        'c.c2': {$exists: false}
      },
      {
        'a': 1,
        'b': 2,
        'd': 4
      }
    ]
}).sort({'e' : -1})

我尝试创建以下索引:

{
    a: 1,
    b: 1,
    'c.c1': 1,
    'c.c2': 1,
    e: 1
}, {name: 'test_1'}

{
    a: 1,
    b: 1,
    d: 1,
    e: 1
}, {name: 'test_2'}

当我在上面的查询中使用explain()时,我看到它在查询阶段并行使用两个索引,但它不使用sorting的索引,这是主要问题。

如果我将test_1索引更改为不包含c.c2字段,并且我使用查询中的exists: false删除此字段,那么我将完全进入explain()我想要的:在查询阶段并行使用两个索引,并使用SORT_MERGE阶段合并两个索引查询。

但我需要$exists: false参数,我不知道如何正确编制索引,因此在使用索引查询的索引后它将使用SORT_MERGE阶段。

0 个答案:

没有答案