java - 如何在 Spring 中使用 MongoDB 强制执行唯一字段
问题描述
我有一个 pojo,其中包含两个需要唯一的字段,即 id 和电子邮件。所以我@Indexed(unique = true)
像这样将注释添加到必要的字段中
public class User {
@Id
@Indexed(unique = true)
private String id;
@Indexed(unique = true)
private String email;
private int money;
然后我对其进行了测试,但没有强制执行。所以我搜索了一下,我在这里找到了以前的答案 - Spring Data:MongoDB 文档中的唯一字段,随后删除了集合,添加spring.data.mongodb.auto-index-creation=true
到我的 application.properties 文件并再次尝试。
但是,仍然没有强制执行唯一字段!我看到有另一个答案在使用ensureIndex()
,但它也有一个很好的评论,从来没有回答过-Why do we need to use the annotation if all the work is done on mongoTemplate?
因此,由于问题已经足够老了,显然唯一可行的答案已被贬低(新方法是 using createIndex()
),我认为是时候推出新版本了。是否可以要求 mongo 集合中的列在 Spring Boot 中是唯一的?
解决方案
推荐阅读
- r - 当组发生变化时聚合一个新变量
- ios -
- excel - 如果在另一列中具有最大值,则使用“1”标记重复项
- google-cloud-platform - 如何取消我的 Google Cloud Platform 帐户的免费试用?
- python - 在 Python 中复制 chrome devtools 网络 XHR
- bash - Git 在函数内部时不会创建 .gitconfig
- node.js - 如果在 https 中,则无法使用 req.get('Referrer') 获取完整路径
- sql - 发现不良信用后退出所有交易
- linux - 循环遍历 Bash 中的一部分非顺序目录
- mysql - 如何使用 SQL 按字符串中给定字符的数量排序?