使用 Spring 数据更新 MongoDB $jsonSchema
Update MongoDB $jsonSchema with Spring Data
Spring 数据文档 describes 如何使用给定的 $jsonSchema
创建集合,以及如何执行验证查询。
有没有办法更新现有集合的$jsonSchema
? MongoTemplate.createCollection()
对于现有结果 MongoCommandException
,错误代码为 48(集合存在),架构未更新。
好的,貌似Spring数据中没有现成的方法,但是实现起来还是挺简单的:
<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
权限。
Spring 数据文档 describes 如何使用给定的 $jsonSchema
创建集合,以及如何执行验证查询。
有没有办法更新现有集合的$jsonSchema
? MongoTemplate.createCollection()
对于现有结果 MongoCommandException
,错误代码为 48(集合存在),架构未更新。
好的,貌似Spring数据中没有现成的方法,但是实现起来还是挺简单的:
<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
权限。