mongodb - 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"]
})
这可能吗
解决方案
是的,可以使用唯一索引。
该索引确保所有文档中数组中的所有元素都是唯一的。
db.getCollection('test').createIndex({ tags : 1},{ unique: true })
检查MongoDB 中的Mulitykey索引及其约束。
推荐阅读
- javascript - 将 Base64 字符串转换为 Javascript Uint16Array?
- json - 选择状态不指向下一个状态 - AWS
- c++ - Qtcreator 从文件而不是终端获取标准输入
- java - 片段获取错误的共享偏好数据
- python - 无法启动 jupyter 笔记本
- python - 在 Pandas 中进行分组和插值
- android - 如何在 Fragment 的 Recyclerview 中放置 EditText 和发送按钮?
- php - 如果字符串与数据库中的部分匹配,如何检查 MySQL?
- python - MySQL cur.execute 格式
- c# - 不要等待类实例初始化并继续使用代码c#