我有一个 MongoDB 集合,其中的文档具有我们将在下面看到的字段。我正在尝试使用将在我的过滤器查询中使用的表达式来构建部分索引。
这是
Partial Index
创建命令
db.reviews.createIndex(
{
catalog_id: 1,
product_id: 1,
score: -1,
created_at: -1
},
{
name: "reviews_only_fetch_by_catalog_product",
partialFilterExpression: {
$or: [
{ comments: { $exists: true } },
{ images: { $exists: true } },
{ videos: { $exists: true } }
]
}
}
)
当我运行以下查询时,我期望部分索引得到利用,因为过滤器表达式是部分索引表达式的一个子集。
{
$and: [
{
catalog_id: '100'
},
{
$or: [
{
comments: {
$exists: true
}
},
{
images: {
$exists: true
}
},
{
videos: {
$exists: true
}
}
]
}
]
}
但令人惊讶的是,
explain plan
生成了一个COLLSCAN
而不是使用索引。为什么完全按照索引定义中定义的$or
过滤器不适用于查询?
虽然下面的查询能够利用索引。
{
catalog_id: '100',
comments: {
$exists: true
}
}
MongoDB 版本 -
6.0.4