在MongoDB中,对于这个查询,最合适的索引方案是什么?

编程语言 2026-07-12

我有一个大约包含2 亿条文档的集合,需要查询其中一个特定子集。 对于这种情况,有没有办法建立索引? 我不知道该怎么做,才能帮助解决 $or!

{
        $match: {
          deviceId: { $in: someIds },
          $expr: {
            $or: [
              { $eq: ['$path', 'one-particular-path'] },
              { $in: ['$abc', ['true', 'false']] }, // There also null we ignore
              { $eq: ['$type', 'fixed-type'] },
            ],
          },
        },
      },

我猜我需要做的是用这个查询对集合进行预先物化,这样在任何 $match中就不用再担心 $or。

解决方案

那个 $expr 的作用是什么?这个查询在语义上与下面这条完全等价:

{
  $match: {
    deviceId: { $in: someIds },
    $or: [
      { path: 'one-particular-path' },
      { abc: { $in: ['true', 'false'] } },
      { type: 'fixed-type' }
    ]
  }
}

你可以用三个索引来覆盖它:

{ deviceId: 1, path: 1 }

{ deviceId: 1, abc: 1 }

{ deviceId: 1, type: 1 }

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章