mongodb - 当字段不为空时创建部分索引

标签 mongodb indexing

我正在尝试在字段上创建部分索引,但仅当该字段不为空时。换句话说,我希望能够让许多文档能够存储空值,但是对于在该字段中实际具有值的文档,我希望该值是唯一的。这是我尝试使用的代码

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 使用部分索引过滤器您必须使用以下过滤器:
{ "email": { "$eq": "foo@mail.com", "$type": "string" } }
// or
{ $and: [{ "email": "foo@mail.com" }, { "email": { $type: "string" } }] }
Playground

关于mongodb - 当字段不为空时创建部分索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64066830/

相关文章:

mongodb - 为什么我们不能在mongodb中自己定义主键?

mongodb - Scala 中的 Monad 转换器用于理解处理选项并收集错误消息

javascript - 有什么方法可以更改数组元素索引,使其从 1, 2, 3, 4 而不是 0, 1 ,2, 3 开始?

python - 获取 ndarray 中 N 个最高值的索引

indexing - Lucene IndexWriter.Close() 与 indexWriter.Commit()

ruby-on-rails - 使用 MongoMapper 创建用于编辑嵌入文档的表单

mysql - 具有全文搜索功能的海量数据库 - Sphinx、Lucene、Cassandra、MongoDB、CouchDB

performance - 未使用 smallint[] 列上的 GIN 索引或错误 "operator is not unique"

swift - 从 allCases 获取枚举案例索引的通用函数

mongodb - 聚合仅返回嵌套数组 mongoose 中第一个匹配的键