如何从 spring 的 mongo 模板执行 mongo 查询?

How to execute mongo query from spring's mongo template?

我正在尝试从 spring 框架的 mongoTemplete 的 executeCommand 执行类似 "db.post.find().pretty()" 的查询。但我做不到?有没有办法直接从 mongotempelate 执行上述查询?感谢任何帮助。

这是我的代码:

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

当然可以,但是您应该传递一个 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);