【问题标题】:Update MongoDB $jsonSchema with Spring Data使用 Spring Data 更新 MongoDB $jsonSchema
【发布时间】:2019-11-18 16:12:27
【问题描述】:
Spring Data 文档describes 如何使用给定的$jsonSchema 创建集合,以及如何执行验证查询。
有没有办法为现有集合更新$jsonSchema?现有的 MongoTemplate.createCollection() 导致 MongoCommandException 错误代码为 48(集合存在),架构未更新。
【问题讨论】:
标签:
mongodb
spring-data
spring-data-mongodb
jsonschema
【解决方案1】:
好吧,Spring Data 中貌似没有现成的方法,但是实现起来还是很简单的:
<T> void updateSchema(MongoTemplate template, Class<T> entityClazz, MongoJsonSchema schema) {
template.executeCommand(new Document(Map.of(
"collMod", template.getCollectionName(entityClazz),
"validator", schema.toDocument()
)));
}
另外请记住,默认的readWrite 角色是不够的,用户需要拥有collMod 权限。