springmongodb-java

Mongodb query constructor to take raw query string Java


I am trying to come up with a concept to take a query string and have it passed into something like this via a query object:

returnList = mongoTemplateTracking.find(query,TrackingData.class, COLLECTION_NAME);

I've been looking at the constructors of both the Query and Criteria classes to see if they could take a raw string such as:

 "ID" : "32399a"

Instead of building up the Criteria object via Criteria.where().is() etc..

I have seen the method

protected <T> List<T> doFind(String collectionName,
                 com.mongodb.DBObject query,
                 com.mongodb.DBObject fields,
                 Class<T> entityClass)

However as I am autowiring the mongoTemplateTracking into my class I cannot access this method.


Solution

  • MongoDB query language ("MQL") is easily expressed in JSON form. So if you have a string expression like:

    String s = "{\"$or\": [ {\"name\": \"buzz\"}, {\"age\": {\"$lt\": 20 }} ] }";
    

    then you can easily parse it with this util:

    import com.mongodb.util.JSON;
    DBObject query = (DBObject) JSON.parse(s);
    yourCollection.find(query);
    

    Take a look at In Java, is there a way to write a string literal without having to escape quotes? to make the escaping of quotes in long query expressions a little easier.