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 ?
Add a comment
|
1 Answer
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);
}
7 Comments
Mohammed shebin
Wow. Thanks for this . I was stuck and waiting for a solution . Thanks a lot :)
chridam
@Mohammedshebin No worries, happy to help :)
Kanagavelu Sugumar
@chridam Hi, How to support aggregate query like db.CollectionName.aggregate( [ {$match:{"st":"i"}}, {$group:},{}.. ]) ...?
chridam
@KanagaveluSugumar The Aggregation Framework support in Spring Data MongoDB is based on the key abstractions
Aggregation, AggregationOperation and AggregationResults where Aggregation represents a MongoDB aggregate operation and holds the description of the aggregation pipeline instructions. Aggregations are created by invoking the appropriate newAggregation(…) static factory Method of the Aggregation class which takes the list of AggregateOperation as a parameter next to the optional input class. The aggregate operation is executed by the aggregate() method of the MongoTemplate.Kanagavelu Sugumar
Thanks! But the question is can i pass json aggregate query string directly to BasicQuery/JSON.parse() like above you have mentioned { age : { $lt : 50 } } ..?
|