我正在尝试在字段上创建部分索引,但仅当该字段不为空时。换句话说,我希望能够让许多文档能够存储空值,但是对于在该字段中实际具有值的文档,我希望该值是唯一的。这是我尝试使用的代码
db.account.createIndex({ "email": 1 }, { unique: true, partialFilterExpression: { "email": { $ne: null } }})
根据我的理解,这应该索引 email
字段不等于 null 时。但它给出了错误:
"unsupported expression in partial index: $not email $eq null"
我试图改变 $ne: null
至 $exists: true
,但是已经有多个文档的 email 字段为空值,所以它也抛出了一个错误。我的架构有一个文档的电子邮件字段,所以每个文档都会自动有一个 email
字段,含义 $exists: true
无论如何都行不通。只有在字段不为空时才能索引字段的任何帮助都会很棒。
最佳答案
$ne
不支持表达式运算符,
As per MongoDB Partial Index supported expressions are: equality expressions (i.e. field: value or using the
$eq
operator),$exists: true
expression,$gt
,$gte
,$lt
,$lte
expressions,$type
expressions,$and
operator at the top-level only,
您可以使用
$type
要检查的是 string
像这样{ "email": { $type: "string" } }
,因为空类型是“空”。NOTE:
As noted in the query coverage documentation for partial indexes:
Since MongoDB will not use the partial index for a query or sort operation if using the index results in an incomplete result set.
To use the partial index, a query must contain the filter expression (or a modified filter expression that specifies a subset of the filter expression) as part of its query condition.
前任。 对$type
使用部分索引过滤器您必须使用以下过滤器:Playground{ "email": { "$eq": "foo@mail.com", "$type": "string" } } // or { $and: [{ "email": "foo@mail.com" }, { "email": { $type: "string" } }] }
关于mongodb - 当字段不为空时创建部分索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64066830/