java - 是否可以使用 spring-data-mongodb 1.10 创建 Mongo View ?

标签 java spring mongodb spring-data-mongodb

我有一个简单的要求,即能够从我的 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/

相关文章:

java - 如何为 Mac/Windows 捆绑 Java 应用程序?

java - AsyncTask : ClassCastException: java. lang.Object[] 无法转换为 java.lang.String[]

java - Spring 测试中的缓存上下文,即使加载失败也是如此

java - 多个 Spring 应用程序的单一集成测试

node.js - NodeJS 和 mongoose - 查找上一小时的记录

node.js - 特定帖子上收集的所有字段的总和

java - java中字符串的字体设置

java - Apache CollectionUtils 的良好用途

java - Apache 、汤姆猫 : Load-balancing not using common session ID's

java - mogodb4.0中通过java驱动对子文档进行排序