Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 480
Mohammed shebin Avatar asked Nov 02 '15 05:11

Mohammed shebin


People also ask

Can I use Spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

What is @document annotation in spring boot?

@Document is an annotation provided by Spring data project. It is used to identify a domain object, which is persisted to MongoDB. So you can use it to map a Java class into a collection inside MongoDB. If you don't use Spring Data, you don't need this annotation.

How does spring boot store JSON objects in MongoDB?

To store raw json object/array, all you have to do is to declare the type as "Object" in the Pojo and/or DTO level on your server side. The "Object" type will work with Spring Data and MapStruct too. Then on the client side, you can send your json data as a json data.


1 Answers

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); 
} 
like image 177
chridam Avatar answered Oct 12 '22 03:10

chridam