【问题标题】:How to execute mongo query from spring's mongo template?如何从spring的mongo模板执行mongo查询?
【发布时间】:2017-03-27 09:23:44
【问题描述】:

我正在尝试从 spring 框架的 mongoTemplete 的 executeCommand 执行诸如“db.post.find().pretty()”之类的查询。但是我做不到?有没有办法直接从mongotempelate执行上面的查询?任何帮助表示赞赏。

这是我的代码:

public CommandResult getMongoReportResult(){
    CommandResult result=mongoTemplate.executeCommand("{$and:[{\"by\":\"tutorials point\"},{\"title\": \"MongoDB Overview\"}]}");
    return result;
}

【问题讨论】:

    标签: java spring mongodb mongotemplate


    【解决方案1】:

    当然可以,但是您应该传递 BasicDBObject 作为参数,而不是字符串,如下所示: (并且您的命令格式不正确,请参阅find command

    BasicDBList andList = new BasicDBList();
    andList.add(new BasicDBObject("by", "tutorials point"));
    andList.add(new BasicDBObject("title", "MongoDB Overview")); 
    BasicDBObject and = new BasicDBObject("$and", andList);
    BasicDBObject command = new BasicDBObject("find", "collectionName");
    command.append("filter", and); 
    mongoTemplate.executeCommand(command);
    

    【讨论】:

    • 感谢您的快速回复。但是我们能否构建一个系统,将 mongo 字符串查询作为输入并在不为每个条件创建 DBObject 的情况下执行它?例如我的输入查询是:{'likes': {$gt:10}, $or: [{'by': 'tutorials point'},{'title': 'MongoDB Overview'}]} 如果我的输入查询大小比上面的方法可能很大。有没有什么方法可以直接在mongotempelate中执行上面的查询?谢谢
    • @PremSingh 是的,你可以,但你应该避免这样做,因为你的代码很快就会变得不可读并且很难维护。您发布的代码不起作用,因为命令错误(缺少filterfind,请参阅docs.mongodb.com/manual/reference/command/find
    猜你喜欢
    • 2021-08-14
    • 1970-01-01
    • 2019-11-17
    • 2022-01-17
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    相关资源
    最近更新 更多