是否可以使用 spring-data-mongo 1.10 创建 Mongo 视图?
Is it possible to create a Mongo view using spring-data-mongo 1.10?
我有一个简单的要求,即能够从我的 Java 应用创建一个 Mongo 视图。我们正在使用 3.4 Mongo 驱动程序和 spring-data-mongo 1.10.2。 The Mongo docs for db.createCollection
表示你通过在选项中包含 viewOn
创建一个视图,但是 mongoTemplate.createCollection
使用的 CollectionOptions
class 没有这个 属性.
我查看了 s-d-m 2.2 版的源代码,但仍然没有看到它受支持。如何创建视图?
我能够让它工作。下面是方法:
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
是 Java class 带有指定 mongo 集合的 @Document
注释。我在这里所做的是基于其基础集合在模型上创建一个视图。 viewDefinition
是视图约束,一个String
如:"{deleted: {$ne: true}}"
.
我有一个简单的要求,即能够从我的 Java 应用创建一个 Mongo 视图。我们正在使用 3.4 Mongo 驱动程序和 spring-data-mongo 1.10.2。 The Mongo docs for db.createCollection
表示你通过在选项中包含 viewOn
创建一个视图,但是 mongoTemplate.createCollection
使用的 CollectionOptions
class 没有这个 属性.
我查看了 s-d-m 2.2 版的源代码,但仍然没有看到它受支持。如何创建视图?
我能够让它工作。下面是方法:
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
是 Java class 带有指定 mongo 集合的 @Document
注释。我在这里所做的是基于其基础集合在模型上创建一个视图。 viewDefinition
是视图约束,一个String
如:"{deleted: {$ne: true}}"
.