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.