本文介绍了Mongodb设置唯一字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
TENANT
{ "_ID" : 11, NAME : "ruben", OPERATION :[{OPERATION_ID: 100, NAME : "Check"}] }
如何设置OPERATION_ID具有唯一性以避免重复的值和避免主键之类的空值?
how to set the OPERATION_ID has unique to avoid duplicate values and to avoid null values like primary key?
推荐答案
当您希望OPERATION_ID对于所有租户都是唯一的时,您可以这样做:
When you want the OPERATION_IDs to be unique for all tenants, then you can do it like that:
db.tenants.ensureIndex( { operation.OPERATION_ID : 1 }, { unique:true, sparse:true } );
当您希望每个租户的OPERATION_ID唯一时,以便两个租户都可以拥有operation_ID:100,但是任何租户都不能拥有operation_id:100两次,则必须将租户的_id添加到索引中,以便任何_id和operation_id的给定组合是唯一的.
When you want the OPERATION_IDs to be unique per tenant, so that two tenants can both have the operation_ID:100 but no tenant can have operation_id:100 twice, you have to add the _id of the tenant to the index so that any given combination of _id and operation_id is unique.
db.tenants.ensureIndex( { _id: 1, operation.OPERATION_ID : 1 }, { unique:true, sparse:true } );
这篇关于Mongodb设置唯一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!