spring-projects / spring-projects/spring-data-mongodb

Consider merging duplicate key criteria with $and instead of throwing an exception in Query#addCriteria

Open
#5,209 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type: enhancement
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.