【问题标题】:Spring data with MongoDB Views带有 MongoDB 视图的 Spring 数据
【发布时间】:2020-11-17 19:38:42
【问题描述】:

为了提高我们的查询性能和 API 响应时间,我们通过聚合数据在 MongoDB 上创建了视图。但是,当我们尝试使用 Spring Mongo 模板使用视图时,会遇到一些问题,例如不支持视图。

Caused by: com.mongodb.MongoCommandException: Command failed with error 166 (CommandNotSupportedOnView): 'Namespace aiops.hostView is a view, not a collection' on server 192.168.20.166:30011. The full response is {​​​​​​​"ok": 0.0, "errmsg": "Namespace aiops.hostView is a view, not a collection", "code": 166, "codeName": "CommandNotSupportedOnView"}​​​​​​​
at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175)
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:303)
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:259)

Spring 是否支持开箱即用的 MongoDB 视图?任何例子都会有很大帮助!

提前谢谢你

【问题讨论】:

  • 请问您是如何手动创建视图或使用 spring boot 编码的?我尝试使用 mongoTemlate 来做到这一点,但没有成功我使用了 mongoTemplate.executeCommand(create: "viewName" , viewOwn: "source" , pipeline : [ pip ] ) 我将不胜感激。

标签: spring mongodb spring-data-jpa


【解决方案1】:

这有点老了,但我会留下我的解决方案,以防有人像我一样偶然发现这个问题。

据我所知,您不能使用通常的 Spring Data 方法:您不能使用 @Document(value="YOUR_VIEW_NAME") 注释来注释实体并创建扩展 MongoRepository 类的相关存储库。

但您可以直接从MongoTemplate 查询视图,并传递您的视图名称。

假设您有一个这样定义的用户实体:

public class User {
    @Id
    String id;

    String name;
}

然后你可以将它映射到一个名为“userview”的视图的文档中,并像这样查询它:


Query query = new Query();
query.addCriteria(Criteria.where("name").is("Bob"));

// template is an object of class MongoTemplate that you can inject or autowire
List<User> users = template.find(query, User.class, "userview");

【讨论】:

    【解决方案2】:

    我最近遇到了同样的问题,@gere 所说的并不完全正确,您可以使用带有 spring 数据存储库的视图,但存在一些与视图本身的限制有关的限制。

    在我的例子中,问题是我在表示视图的文档上使用了注释 CompositeIndex 和 Indexed,并且由于 MongoDB 视图使用底层集合索引,因此它没有为自己创建索引的操作命令和当 spring data 尝试在该视图上创建索引时,MongoDB 会引发异常。删除这些注释后,我可以通过我的存储库使用它们。我建议您也使用只读存储库来防止使用保存方法或删除,因为我认为这也是视图限制。如果您搜索,您可以找到只读存储库的示例。

    在您的情况下,您需要找到您尝试对视图不支持的普通集合执行的操作。

    【讨论】:

    • 谢谢@navid_gh!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2020-07-08
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多