MongoDB native query execution in Spring

Hi Team

How I can execute below query in spring or java driver,

db.getCollection(“user”).find( { “userName”: “xyz”} );

entire query comes as string and I should execute the query and return the results as Objects.

Is there a way to execute the entire query string in spring or Java driver.

Hi @Prabaharan_Kathiresa and welcome back :wink: !

Here are a few examples in Java that will probably help you:

You can also check my Java blog post series on the DevHub: (see all the blog post at the bottom of the page).

I also have a Spring starter project that you can check here:


Hello @Prabaharan_Kathiresa,

I don’t think there is a way to run the whole string as a query using Java or Spring Java APIs. But, you can run native queries using available APIs. For example, using Java Driver you can use the db.runCommand. Here is a post with its usage:

There is similar API method with Spring Data MongoDB, using the MongoTemplate class.

Thank you @MaBeuLux88 :grinning:, Blogs are really helpful. In my Scenario complex part is I don’t know the collection name & what Operation(Find or Count) query intends to(and also I should not parse the string to get the collection name and operation).

db.getCollection(“user”).find( { “userName”: “xyz”} );

Second time, I may get the query string as

db.getCollection(“employee”).count( { “empId”: “123”} );

Is there any libraries that can help me to run shell queries from java/spring?

@Prasad_Saya, Thank you for the reply. db.runCommand suits me. Following below
documentation, another learning today.

Is there any libraries that can help me to run shell queries from Java/Spring?

For the query db.getCollection("books").find( { author: "Leo Tolstoy" } ), you can construct a find command query as, for example, db.runCommand({ "find": "books", "filter": { "author": "Leo Tolstoy" } }).

In Java, you can construct it as:

String strCmd = "{ 'find': 'books', 'filter': { 'author': 'Leo Tolstoy' } }";
Document bsonCmd = Document.parse(strCmd);
Document result = db.runCommand​(bsonCmd);
Document cursor = (Document) result.get("cursor");
List<Document> docs = (List<Document>) cursor.get("firstBatch");

In the above code, the variable strCmdis constructed using the collection name and the query filter strings as "books" and "{ 'author': 'Leo Tolstoy' }" respectively, from the actual shell query.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.