Mohammed shebin
Mohammed shebin

Reputation: 479

Spring data mongodb query by json string

My code need to support any query that being sent by the client . The client will be sending the query as a json . I have done this using java mongo driver low level api using following code ,
BasicDBObject queryObject = (BasicDBObject) JSON.parse(whereJson.toString());
As i am a newbie in spring data mongodb , i am unable to find a similar solution in either Query or Criteria classes . I have checked different tutorials and couldn't find any . Is it possible to do in spring data mongodb or should i use low level apis itself ?

Upvotes: 15

Views: 18971

Answers (1)

chridam
chridam

Reputation: 103335

You can create Query instances from a plain JSON String by using BasicQuery object. The following example demonstrates how you can construct a Query instance from a plain JSON String:

BasicQuery query = new BasicQuery("{ age : { $lt : 50 } }");
List<Person> result = mongoTemplate.find(query, Person.class);    

Another way which uses the low-level API:

DBObject dbObject = (DBObject) JSON.parse(query); 
DBCursor cursor = mongoTemplate.getCollection("person").find(dbObject); 

You can then map the return objects back to your Person POJO using the MongoConverter read() method:

List<Person> returnList = new ArrayList<Person>();
while (cursor.hasNext()) { 
    DBObject obj = cursor.next(); 
    Person person = mongoTemplate.getConverter().read(Person.class, obj);  
    returnList.add(person); 
} 

Upvotes: 21

Related Questions