如何为多个字段创建“中”运算符查询?

时间:2019-06-13 10:04:25

标签: mongodb mongodb-query query-performance mongodb-indexes

我有一个收藏集

db.list.insert({ first: "apple", second: "banana" });
db.list.insert({ first: "apple", second: "tree" });
db.list.insert({ first: "orange", second: "tree" });
db.list.insert({ first: "medal", second: "sport" });

我想基于这两个字段查询文档,并且仅在两个字段匹配时才获取文档。

我尝试了以下查询

db.list.find(
  $or: [
     { first: 'apple', second: { $in: ['tree', 'banana']}},
     { first: 'orange', second: { $in: ['tree']}}
  ],
).limit(5);

并为其添加了索引

{first: 1, second: 1}

在查询计划中,它生成的计划数与“或”查询中的谓词数相同。大约有200万个文档,如果在第一个谓词中没有得到5个文档,则它将获取与所有谓词匹配的所有文档,并且查询超时。 还有其他有效的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以通过mongodb 聚合管道使用 $ facet 。这样可以确保仅提取一次文档。这是示例查询

    db.list.aggregate([
    {
        $facet: {
            "condition_1": [
                {
                    "$match": { first: 'apple', second: { $in: ['tree', 'banana']}}
                },
                {
                    "limit": 5
                }
            ],
            "condition_2": [
                {
                    "$match": { first: 'orange', second: { $in: ['tree']}}
                },
                {
                    "limit": 5
                }
            ]
        }
    }
], {allowDiskUse: true})