【问题标题】:MongoDB crazy slow when there is an $or inside of a query using an $and, How to get it to hit the indexMongoDB 在使用 $and 的查询中有 $or 时速度非常慢,如何让它命中索引
【发布时间】:2022-11-02 00:17:15
【问题描述】:

我有一个 MongoDB 集合,其中包含地理编码信息。在某些情况下,我希望允许包含不在定义的地理区域内的促销项目。下面是一个查询示例。

大约需要 8500 毫秒

{
    "$and": [{
            "After.Start": {
                "$gte": ISODate("2022-10-28T00:00:00Z")
            }
        },{
            "$or": [{
                    "LongLat": {
                        "$geoWithin": {
                            "$centerSphere": [[-111.888221740722, 40.760311126708999], 0.012616093290458801]
                        }
                    }
                }, {
                    "ByPass": {
                        "$in": ["5162e"]
                    }
                }
            ]
        }
    ]
}

如果我将其作为两个单独的查询运行,我将无法添加其他条件或对其进行正确排序或分页,但它运行得更快。

~61ms

{
    "$and": [{
            "After.Start": {
                "$gte": ISODate("2022-10-28T00:00:00Z")
            }
        },{
            "LongLat": {
                "$geoWithin": {
                    "$centerSphere": [[-111.888221740722, 40.760311126708999], 0.012616093290458801]
                }
            }
        }
    ]
}

~1ms

{
    "$and": [{
            "After.Start": {
                "$gte": ISODate("2022-10-28T00:00:00Z")
            }
        },{
            "ByPass": {
                "$in": ["5162e"]
            }
        }
    ]
}

我在所有三个字段上都有非复合索引,LongLat 上的索引是 2dsphere。 我还有一个关于 LongLat 和“After.Start”的复合索引。有没有不同的方法可以索引它或者存储数据以添加旁路。

【问题讨论】:

    标签: mongodb indexing mongodb-query


    【解决方案1】:

    您的 $or 条件测试不同的字段,意味着其中一个不使用索引。考虑到性能下降,假设数据集相对较大,并且您有正确的 ByPass 和地理空间索引是公平的。

    您可以检查 explain 正在使用哪些索引。

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2015-09-18
      相关资源
      最近更新 更多