简体   繁体   English

无法使用 Java Spring 引导创建 Mongo 实体化视图

[英]Cannot create Mongo Materialized view using Java Spring Boot

I have a collection name Order with many properties.我有一个包含许多属性的集合名称Order I wanna create a materialized view with 3 fields from Order to destStationList.我想创建一个物化视图,其中包含从Order到 destStationList 的 3 个字段。 I'm using the following java method to do that.我正在使用以下 java 方法来做到这一点。

    private void createMaterializedView() {
        String collectionName = "orders";
        String viewName = "destStationList";

        // Attempt to create the view
        if(mongoTemplate.collectionExists(viewName)){
            mongoTemplate.dropCollection(viewName);
        }

        CommandResult result = mongoTemplate.executeCommand("{" +
                "aggregate: '" + viewName + "', " +
                "pipeline: [ { $project: { travelDate: 1, trainNumber: 1, to: 1 } },  { $merge: { into: \"destStationList\", whenMatched: \"replace\", whenNotMatched: \"insert\" } } ]," +
                "cursor: { }"+
                "}");

        if(result.ok()) {
            LOGGER.info("Successfully created view '{}' on collection '{}'", viewName, collectionName);
        }
        else {
            System.out.println("Failed to create view '" + viewName + "' on collection '" + collectionName + "' - " + result.getErrorMessage());
        }
    }

I have tested the following mongo shell command to check that in my local mongodb.我已经测试了以下 mongo shell 命令来检查我的本地 mongodb。 It works well.它运作良好。

db.runCommand( { 
  aggregate: "order", 
  pipeline: [ { $project: { travelDate: 1, trainNumber: 1, to: 1 } },  { $merge: { into: "destStationList", whenMatched: "replace", whenNotMatched: "insert" } } ],
  cursor: { } 
} );

For your information, I'm using MongoDB version 4.4.供您参考,我使用的是 MongoDB 4.4 版。

The problem is that executing the java method shows that the view is created successfully.问题是执行java方法显示视图创建成功。 But when I run the command mongoTemplate.collectionExists("destStationList") it returns false and also cannot retrieve data by querying from the view.但是当我运行命令mongoTemplate.collectionExists("destStationList")它返回 false 并且也无法通过从视图中查询来检索数据。

在此处输入图像描述

Can anyone please help me with it?任何人都可以帮我吗? How can I create a mongo materialized view using java?如何使用 java 创建 mongo 物化视图?

Should it be collectionName instead of viewName in the aggregate?它应该是collectionName而不是viewName在聚合中?

CommandResult result = mongoTemplate.executeCommand("{" +
            "aggregate: '" + collectionName + "', " +
            "pipeline: [ { $project: { travelDate: 1, trainNumber: 1, to: 1 } },  { $merge: { into: \"destStationList\", whenMatched: \"replace\", whenNotMatched: \"insert\" } } ]," +
            "cursor: { }"+
            "}");

You may also want to use the viewName variable rather than hardcode it into the String.您可能还想使用viewName变量而不是将其硬编码到字符串中。

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

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