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 ?
Yes, DataNucleus JPA allows it, as well as to many other databases.
@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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With