Mongodb setting unique field

放肆的年华 提交于 2019-12-18 06:48:30

问题


 TENANT
  { "_ID" : 11, NAME : "ruben", OPERATION :[{OPERATION_ID: 100, NAME : "Check"}] }

how to set the OPERATION_ID has unique to avoid duplicate values and to avoid null values like primary key?


回答1:


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 } );

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 } );



回答2:


Adding a unique index on OPERATION.OPERATION_ID will ensure that no two distinct documents will contain an element in OPERATION with the same OPERATION_ID.

If you want to prevent a single document from having two elements in OPERATION with the same OPERATION_ID, you can't use unique indexes; you will have to use set update operators (such as $set and $addToSet). You could turn OPERATION into a subdocument keyed by OPERATION_ID, like so:

{ "_ID" : 11, NAME : "ruben", OPERATION : {"100" : {NAME : "Check"} }}

Then you can enforce uniqueness by issuing updates with $set; for example:

db.<collection>.update({NAME: "ruben"}, {$set: {"OPERATION.100.NAME": "Uncheck"}})

Regarding null values: MongoDB doesn't feature non-null constraints on fields (it doesn't even force a given field to have a single type), so you will have to ensure in your application that null values aren't inserted.



来源:https://stackoverflow.com/questions/12395118/mongodb-setting-unique-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!