简体   繁体   English

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

[英]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.

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