簡體   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