3

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.

Will
  • 8,246
  • 16
  • 60
  • 92

4 Answers4

4

JSON.parse(json) was deprecated. use this code:

String s = "{\"$or\": [ {\"name\": \"buzz\"}, {\"age\": {\"$lt\": 20 }} ] }";
Bson bson =  BasicDBObject.parse( json );
collection.find(bson);
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
HungNM2
  • 3,101
  • 1
  • 30
  • 21
2

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.

Community
  • 1
  • 1
Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33
1

if you are using raw query like this: "{\"$or\": [ {\"name\": \"buzz\"}, {\"age\": {\"$lt\": 20 }} ] }"

this is the implementation part:

String queryString= "{\"$or\": [ {\"name\": \"buzz\"}, {\"age\": {\"$lt\": 20 }} ] }";
BasicQuery basicQuery = new BasicQuery(queryString);
mongoTemplate.find(basicQuery, TrackingData.class, COLLECTION_NAME); 
Praveen Kumar Verma
  • 2,988
  • 2
  • 18
  • 31
0

In case, you're using Spring Boot Data.

mongoTemplate.find(new BasicQuery("{salary: {$gt: 50, $lt: 100}, name: {$regex: '^A', $options: ''}}", TestDocument.class);
kkochanski
  • 2,178
  • 23
  • 28