繁体   English   中英

是否可以使用 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。 db.createCollection的 Mongo 文档表明您通过在选项中包含viewOn来创建视图,但mongoTemplate.createCollection使用的CollectionOptions类没有此属性。

我已经将源代码挖掘到 sdm 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是带有指定 mongo 集合的@Document批注的 Java 类。 我在这里所做的是基于模型的底层集合在模型上创建视图。 viewDefinition是视图约束,一个String例如: "{deleted: {$ne: true}}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM