Reputation: 19549
I have a simple requirement to be able to create a Mongo view from my Java app. We're using the 3.4 Mongo driver and 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.
I've dug through source code up to s-d-m version 2.2 and still don't see it supported. How can I create a view?
Upvotes: 2
Views: 1144
Reputation: 19549
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. 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}}"
.
Upvotes: 2