#442 Improve and operation handling

This commit is contained in:
Timo Westkämper 2013-06-15 14:43:55 +03:00
parent 3e0ee276f9
commit 138154a1b7
2 changed files with 24 additions and 8 deletions

View File

@ -20,6 +20,7 @@ import java.util.regex.Pattern;
import org.bson.BSONObject;
import org.bson.types.ObjectId;
import com.google.common.collect.Sets;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
@ -117,9 +118,17 @@ public class MongodbSerializer implements Visitor<Object, Void> {
return asDBObject(asDBKey(expr, 0), "");
} else if (op == Ops.AND) {
BasicDBObject left = (BasicDBObject) handle(expr.getArg(0));
left.putAll((BSONObject) handle(expr.getArg(1)));
return left;
BSONObject lhs = (BSONObject) handle(expr.getArg(0));
BSONObject rhs = (BSONObject) handle(expr.getArg(1));
if (Sets.intersection(lhs.keySet(), rhs.keySet()).isEmpty()) {
lhs.putAll(rhs);
return lhs;
} else {
BasicDBList list = new BasicDBList();
list.add(handle(expr.getArg(0)));
list.add(handle(expr.getArg(1)));
return asDBObject("$and", list);
}
} else if (op == Ops.NOT) {
//Handle the not's child

View File

@ -1,6 +1,6 @@
/*
* Copyright 2011, Mysema Ltd
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -23,6 +23,7 @@ import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mysema.query.mongodb.domain.QDummyEntity;
@ -141,8 +142,9 @@ public class MongodbSerializerTest {
assertQuery(
year.gt(1).and(year.lt(10)),
dbo("year", dbo("$gt", 1)).
append("year", dbo("$lt", 10))
dbo("$and", dblist(
dbo("year", dbo("$gt", 1)),
dbo("year", dbo("$lt", 10))))
);
assertQuery(
@ -216,11 +218,16 @@ public class MongodbSerializerTest {
if (value.length == 1) {
return new BasicDBObject(key, value[0]);
}
return new BasicDBObject(key, value);
}
public static BasicDBList dblist(Object... contents) {
BasicDBList list = new BasicDBList();
for (Object o : contents) {
list.add(o);
}
return list;
}
}