Mongodb setting unique field

2019-01-26 14:47发布

问题:

 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.