spring-projects / spring-projects/spring-data-mongodb
Consider merging duplicate key criteria with $and instead of throwing an exception in Query#addCriteria
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 1.7k
- Forks
- 1.1k
- PR merge metrics
- No merged PRs in 30d
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at Query#addCriteria and trace the InvalidMongoDbApiUsageException path for duplicate keys. Compare it with the existing andOperator() behavior, then define and test whether duplicate criteria should merge under $and while preserving existing behavior for non-conflicting criteria.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, mongodb
- Domain
- database
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100