本文介绍了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 设置唯一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:37