saran3h
saran3h

Reputation: 14022

Search records by values containing given strings

I have a collection:

_id: ObjectId("11313123qeqerq")
products: Array
    0: Object
        name: "ABC-123"

I want to write a Spring criteria query which could find me all the products having name containing ("ABC", "DEF")

Can anyone help me come up with a query? Something in the lines of:

query.addCriteria(where(products).elemMatch(where(name).in("ABC", "DEF"));

Upvotes: 0

Views: 39

Answers (1)

IQbrod
IQbrod

Reputation: 2265

Your method in() does check an exact equality.
You should use LIKE as in SQL. In criteria it does translate as like():

criteria.add(Restrictions.disjunction()
    .add(Restrictions.like("name", "ABC", MatchMode.ANYWHERE))
    .add(Restrictions.like("name", "DEF", MatchMode.ANYWHERE))
);

The criterion does look for strings containing either ABC or DEF anywhere.
Use ilike() for a comparison non case-sensitive.

Upvotes: 1

Related Questions