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

Prem Singh picture Prem Singh · Mar 27, 2017 · Viewed 7.2k times · Source

I am trying to execute queries like "db.post.find().pretty()" from executeCommand of mongoTemplete of spring framework. But I am unable to do it?Is there a way to execute queries like above directly from mongotempelate? Any help is appreciated.

Here is my code:

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

Answer

felix picture felix · Mar 27, 2017

yes of course, but you should pass a BasicDBObject as parameter, and not a String, like this: (and your command wasn't formatted correctly, see 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);