Mongo 在使用匹配 + 排序操作的聚合期间使用错误的索引 [英] Mongo using the wrong index during aggregation with match+sort operations

查看:23
本文介绍了Mongo 在使用匹配 + 排序操作的聚合期间使用错误的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 MongoDB 版本 4.2.0.我有一个包含以下索引的集合:

I'm using MongoDB version 4.2.0. I have a collection with the following indexes:

{uuid: 1},
{unique: true, name: "uuid_idx"}

{field1: 1, field2: 1, _id: 1},
{unique: true, name: "compound_idx"}

执行此查询时

aggregate([
  {"$match": {"uuid": <uuid_value>}}
])

规划器正确选择了uuid_idx.

添加此排序子句时

aggregate([
  {"$match": {"uuid": <uuid_value>}},
  {"$sort": {"field1": 1, "field2": 1, "_id": 1}}
])

规划器选择compound_idx,这会使查询变慢.

the planner selects compound_idx, which makes the query slower.

我希望 sort 子句在这种情况下不会产生影响.为什么 Mongo 在两种情况下都不使用 uuid_idx 索引?

I would expect the sort clause to not make a difference in this context. Why does Mongo not use the uuid_idx index in both cases?

编辑:稍微澄清一下,我知道有一些解决方法可以使用正确的索引,但我正在寻找为什么这不会自动发生的解释(如果可能,请提供官方文档的链接).谢谢!

EDIT: A little clarification, I understand there are workarounds to use the correct index, but I'm looking for an explanation of why this does not happen automatically (if possible with links to the official documentation). Thanks!

推荐答案

如果您可以使用 find 而不是聚合,它将使用正确的索引.所以这仍然是聚合管道中的问题.

If you can use find instead of aggregate, it will use the right index. So this is still problem in aggregate pipeline.

这篇关于Mongo 在使用匹配 + 排序操作的聚合期间使用错误的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆