是否可以使用spring-data-mongo 1.10创建Mongo视图?

问题描述 投票:1回答:1

我有一个简单的要求,就是能够从我的Java应用程序创建Mongo视图。我们正在使用3.4 Mongo驱动程序和spring-data-mongo 1.10.2。 The Mongo docs for db.createCollection表示您通过在选项中包含db.createCollection来创建视图,但是viewOn使用的CollectionOptions类没有此属性。

我已经研究了源代码直到s-d-m 2.2版,但仍然看不到它的支持。如何创建视图?

java spring mongodb spring-data-mongodb
1个回答
0
投票

我能够使它正常工作。下面是方法:

mongoTemplate.createCollection

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类。我在这里所做的是基于模型的基础集合在模型上创建视图。 @Document是视图约束,viewDefinition如:String

© www.soinside.com 2019 - 2024. All rights reserved.