Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb setting unique field

 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?

like image 374
Ramya Avatar asked Sep 12 '12 19:09

Ramya


People also ask

How do I get unique values of a column in MongoDB?

To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.

How do I show only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do you create a unique index?

Right-click the table on which you want to create a unique index and select Design. On the Table Designer menu, select Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box.

What is a unique index?

Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.


1 Answers

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 } );
like image 123
Philipp Avatar answered Nov 11 '22 22:11

Philipp