使用Spring Data更新MongoDB$jsonSchema



Spring Data文档描述了如何使用给定的$jsonSchema创建集合,以及如何执行验证查询。

是否有方法更新现有集合的$jsonSchema?现有的MongoTemplate.createCollection()导致MongoCommandException,错误代码为48(集合存在(,架构未更新。

好的,看起来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权限。

最新更新