Morphia's Criteriacontainer overwrites previously set "$or" statement
See original GitHub issueI am using Morphia’s Query api, and found that my “or” expression is getting overwritten when the expression takes a certain shape. The full expression that I tried to craft was:
$and: [
{ $or: [ { fieldA: "a"}, { fieldB: "b"} ] } , // fieldA == a OR fieldB == b
{ $and: [
{ fieldC: "c" }, // fieldC == c AND (fieldD = d OR fieldE = e)
{ $or: [ { fieldD: "d" }, { fieldE: "e" } ] }
]
Here’s how I’m building the query:
query.and(
query.or(
query.criteria("fieldA").equal("A"),
query.criteria("fieldB").equal("B")
),
query.and(
query.criteria("fieldC").equal("C"),
query.or(
query.criteria("fieldD").equal("D"),
query.criteria("fieldE").equal("E")
)
)
);
The resultant query’s toString() form :
{ query: { "$or" : [{ "fieldD" : "D" }, { "fieldE" : "E" }], "fieldC" : "C" }
It’s missing the section, “$or: [ {fieldA: A}, { fieldB: B} ]”.
I understand that the api modifies the internal state of the query object, and so I suspect that perhaps I’m not using the API correctly. If so, could you please provide some guidance on how my original expression could be built programmatically using the Query object?
I digged into Morphia’s CriteriaContainerImpl.java, and saw that the addTo(final DBObject obj) method descends into the nested expression and passes the running DBObject:
} else {
// no dup field names, don't use $and
for (final Criteria child : children) {
child.addTo(obj); <--- this is the running DBObject
}
}
Then, when it starts evaluating the child “$or” expression, it replaces the pre-existing “$or” stored in the propagated DBObject:
final BasicDBList or = new BasicDBList();
for (final Criteria child : children) {
final BasicDBObject container = new BasicDBObject();
child.addTo(container);
or.add(container);
}
obj.put("$or", or);
Thanks for your time. If this is not the proper place to be posting this, then please kindly direct me to where I should go for these type of questions.
Issue Analytics
- State:
- Created 5 years ago
- Comments:12 (6 by maintainers)
@evanchooly thank you so much. That helps!
https://morphia.dev/