Morphia - Merging a complex query with a complex criteria

391 Views Asked by At

I am converting filters from the client to a QueryImpl using the setQueryObject method. When I try to add another complex criteria to that query my original query is moved to a field named baseQuery and the new criteria is the query field. When the query is executed only the new criteria is used and the baseQuery is not used. It only happens when the client query is formatted like this: { "$or" : [{ "field1" : { "$regex" : "value1", "$options" : "i"}},...]} and the new criteria is formatted in the same way(meaning an $or operation). It seems that when I try to merge 2 $or queries it happens but when I merge $or with $and it concatenates the queries properly. Am I using it wrong or is it a genuine bug? Edit: Code:

public static List<Entity> getData(client.Query query) {
QueryImpl<Entity> finalQuery = Morphia.realAccess().extractFromQuery(Entity.class,query);
finalQuery.and(finalQuery.or(finalQuery.criteria("field").equal(false), finalQuery.criteria("field").doesNotExist()));
return finalQuery.asList();
}

public <E> QueryImpl<E> extractFromQuery(Class<E> clazz, client.Query query) {
    QueryImpl<E> result = new QueryImpl<E>(clazz,this.db.getCollection(clazz),this.db);
result.setQueryObject(query.getFiltersAsDBObject);
return result;
}
2

There are 2 best solutions below

9
On

QueryImpl and setQueryObject() are internal constructs. You really shouldn't be using them as they may change or go away without warning. You should be using the public query builder API to build up your query document.

0
On

I am having the same problem, It seems to be working when I do this: finalQuery.and(); finalQuery.and(finalQuery.or(finalQuery.criteria("field").equal(false), finalQuery.criteria("field").doesNotExist())); It is kind of ugly and would love to hear if someone have a different approach, but the only way I was able to find to convert the data from the client side which is a DBObject is to use the setQueryObject() of QueryImpl.