When building queries dynamically, it's fairly common to end up calling addCriteria() multiple times with criteria that share the same key — for example, applying both a lower and upper bound on the same field via separate code paths.
Currently, addCriteria() throws an InvalidMongoDbApiUsageException in this case:
query.addCriteria(where("amount").gte(100));
query.addCriteria(where("amount").lte(500)); // throws
The workaround is to collect all criteria into a list and wrap them with andOperator(), which works fine but isn't obvious and forces callers to restructure their query-building logic just to avoid the exception.
It would be nice if addCriteria() (or a new variant) could automatically merge conflicting criteria under a $and instead of throwing. MongoDB handles this just fine:
{ "$and": [ { "amount": { "$gte": 100 } }, { "amount": { "$lte": 500 } } ] }
I understand there might be concerns around changing existing behavior, so a separate method like addCriteriaOrAnd() or a flag on Query could be an option.
When building queries dynamically, it's fairly common to end up calling
addCriteria()multiple times with criteria that share the same key — for example, applying both a lower and upper bound on the same field via separate code paths.Currently,
addCriteria()throws anInvalidMongoDbApiUsageExceptionin this case:The workaround is to collect all criteria into a list and wrap them with
andOperator(), which works fine but isn't obvious and forces callers to restructure their query-building logic just to avoid the exception.It would be nice if
addCriteria()(or a new variant) could automatically merge conflicting criteria under a$andinstead of throwing. MongoDB handles this just fine:{ "$and": [ { "amount": { "$gte": 100 } }, { "amount": { "$lte": 500 } } ] }I understand there might be concerns around changing existing behavior, so a separate method like
addCriteriaOrAnd()or a flag onQuerycould be an option.