I want to add the unique index to a field ignoring null values in the unique indexed field and ignoring the documents that are filtered based on partialFilterExpression.
我想将唯一索引添加到字段中,忽略唯一索引字段中的空值,并忽略基于partialFilterExpression过滤的文档。
The problem is Sparse indexes can't be used with the Partial index.
问题是稀疏索引不能与Partial索引一起使用。
Also, adding unique indexes, adds the null value to the index key field and hence the documents can't be ignored based on $exist criteria in the PartialFilterExpression.
此外,添加唯一索引会将空值添加到索引键字段,因此无法根据PartialFilterExpression中的$ exist条件忽略文档。
Is it possible in MongoDB 3.2 to get around this situation?
是否有可能在MongoDB 3.2中解决这种情况?
2 个解决方案
#1
15
I am adding this answer as I was looking for a solution and didn't find one. This may not answer exactly this question or may be, but will help lot of others out there like me.
我正在寻找一个解决方案而没有找到一个解决方案。这可能无法回答这个问题或者可能是,但会像我一样帮助很多其他人。
Example. If the field with null
is houseName
and it is of type string
, the solution can be like this
例。如果带有null的字段是houseName并且它是string类型,则解决方案可以是这样的
db.collectionName.createIndex(
{name: 1, houseName: 1},
{unique: true, partialFilterExpression: {houseName: {$type: "string"}}}
);
This will ignore the null
values in the field houseName
and still be unique.
这将忽略字段houseName中的空值,并且仍然是唯一的。
#2
3
Yes, you can create partial index in MongoDB 3.2
是的,您可以在MongoDB 3.2中创建部分索引
Please see https://docs.mongodb.org/manual/core/index-partial/#index-type-partial
请参阅https://docs.mongodb.org/manual/core/index-partial/#index-type-partial
MongoDB recommend usage of partial index over sparse index. I'll suggest you to drop your sparse index in favor of partial index.
MongoDB建议在稀疏索引上使用部分索引。我建议你放弃你的稀疏索引,转而支持部分索引。
#1
15
I am adding this answer as I was looking for a solution and didn't find one. This may not answer exactly this question or may be, but will help lot of others out there like me.
我正在寻找一个解决方案而没有找到一个解决方案。这可能无法回答这个问题或者可能是,但会像我一样帮助很多其他人。
Example. If the field with null
is houseName
and it is of type string
, the solution can be like this
例。如果带有null的字段是houseName并且它是string类型,则解决方案可以是这样的
db.collectionName.createIndex(
{name: 1, houseName: 1},
{unique: true, partialFilterExpression: {houseName: {$type: "string"}}}
);
This will ignore the null
values in the field houseName
and still be unique.
这将忽略字段houseName中的空值,并且仍然是唯一的。
#2
3
Yes, you can create partial index in MongoDB 3.2
是的,您可以在MongoDB 3.2中创建部分索引
Please see https://docs.mongodb.org/manual/core/index-partial/#index-type-partial
请参阅https://docs.mongodb.org/manual/core/index-partial/#index-type-partial
MongoDB recommend usage of partial index over sparse index. I'll suggest you to drop your sparse index in favor of partial index.
MongoDB建议在稀疏索引上使用部分索引。我建议你放弃你的稀疏索引,转而支持部分索引。