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