Skip to content

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

Description

@anjeongkyun

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions