[英]Is it possible to create a Mongo view using spring-data-mongo 1.10?
I have a simple requirement to be able to create a Mongo view from my Java app.我有一个简单的要求,即能够从我的 Java 应用程序创建 Mongo 视图。 We're using the 3.4 Mongo driver and spring-data-mongo 1.10.2.
我们使用的是 3.4 Mongo 驱动程序和 spring-data-mongo 1.10.2。 The Mongo docs for
db.createCollection
indicate you create a view by including viewOn
in the options, but the CollectionOptions
class that is used by mongoTemplate.createCollection
doesn't have this property. db.createCollection
的 Mongo 文档表明您通过在选项中包含viewOn
来创建视图,但mongoTemplate.createCollection
使用的CollectionOptions
类没有此属性。
I've dug through source code up to sdm version 2.2 and still don't see it supported.我已经将源代码挖掘到 sdm 2.2 版,但仍然没有看到它受支持。 How can I create a view?
如何创建视图?
I was able to get this working.我能够让这个工作。 Below is the method:
下面是方法:
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
is the Java class with the @Document
annotation that specifies the mongo collection. model
是带有指定 mongo 集合的@Document
批注的 Java 类。 What I was doing here was creating a view on a model based on its underlying collection.我在这里所做的是基于模型的底层集合在模型上创建视图。
viewDefinition
are the view constraints, a String
such as: "{deleted: {$ne: true}}"
. viewDefinition
是视图约束,一个String
例如: "{deleted: {$ne: true}}"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.