首页 > 解决方案 > mongodb防止数组元素在文档中重复

问题描述

假设我插入以下示例文档

   db.getCollection("test").insert({
      _id: new UUID(),
      name: "abc",
      tags: ["A", "B"]
   })

当我尝试再次添加另一个带有标签“B”的文档时,我需要 mongo 来引发约束违规。

   db.getCollection("test").insert({
      _id: new UUID(),
      name: "pqr",
      tags: ["B", "C"]
   })

这可能吗

标签: mongodbconstraints

解决方案


是的,可以使用唯一索引。

该索引确保所有文档中数组中的所有元素都是唯一的。

db.getCollection('test').createIndex({ tags : 1},{ unique: true })

检查MongoDB 中的Mulitykey索引及其约束。


推荐阅读