我有一个简单的要求,即能够从我的 Java 应用程序创建 Mongo View 。我们使用 3.4 Mongo 驱动程序和 spring-data-mongo 1.10.2。 The Mongo docs for db.createCollection
指示您通过在选项中包含 viewOn
来创建 View ,但 mongoTemplate.createCollection
使用的 CollectionOptions
类没有此属性.
我已经研究了 s-d-m 版本 2.2 的源代码,但仍然没有看到它受支持。如何创建 View ?
最佳答案
我能够让这个工作。方法如下:
private void createView(BaseEntity model, String viewName, String viewDefinition) {
// Get the model's @Document annotation so we can determine its collection
Document doc = model.getClass().getAnnotation(Document.class);
Assert.notNull(doc, "Error - @Document annotation is null for model class: " + model.getClass().getSimpleName());
// Attempt to create the view
CommandResult result = mongoTemplate.executeCommand("{" +
"create: '" + viewName + "', " +
"viewOn: '" + doc.collection() + "', " +
"pipeline: [{$match: " + viewDefinition + "}]" +
"}");
if(result.ok()) {
LOGGER.info("Successfully created view '{}' on collection '{}'", viewName, doc.collection());
}
else {
throw new ViewCreationBeanException(
"Failed to create view '" + viewName + "' on collection '" + doc.collection() + "' - " + result.getErrorMessage(),
result.getException()
);
}
}
model
是带有指定 mongo 集合的 @Document
注释的 Java 类。我在这里所做的是根据模型的底层集合创建模型 View 。 viewDefinition
是 View 约束,一个String
,例如:"{deleted: {$ne: true}}"
。
关于java - 是否可以使用 spring-data-mongodb 1.10 创建 Mongo View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038373/