Cannot create Mongo Materialized view using Java Spring Boot

Viewed 28

I have a collection name Order with many properties. I wanna create a materialized view with 3 fields from Order to destStationList. I'm using the following java method to do that.

    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. 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.

The problem is that executing the java method shows that the view is created successfully. But when I run the command mongoTemplate.collectionExists("destStationList") it returns false and also cannot retrieve data by querying from the view.

enter image description here

Can anyone please help me with it? How can I create a mongo materialized view using java?

1 Answers

Should it be collectionName instead of viewName in the aggregate?

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.

Related