Morphia query example : hasAnyOf() and hasNoneOf()

Morphia query example : hasAnyOf() and hasNoneOf()

Like the IN operator in SQL, hasAnyOf() lets you test against multiple values for the field you are querying on. If any of these values matches the field’s value, then the entity will be returned. hasAnyOf() corresponds to the $in operator of mongoDB.

hasNoneOf() works the exact oposite way: if any of the tested values match the content of the field, the entity will not be considered a match to your query. hasNoneOf() corresponds to the $nin operator of mongoDB. You can also use both methods to test an array or collection field in your entity, in which case, an entity / document will be a match if ANY of the values in the field match ANY of the values of the query.


hasAnyOf() and hasNoneOf() example :

Notice that in the  hasAnyOf() example above will return entities where the interests field either contains chocolate OR sport cars. If you need to find users interested in chocolate AND sport cars you need to build and AND clause either implicitly or explicitely. The easiest way of doing is to do it by using the hasAllOf() method detailed in a subsequent post.


Morphia documentation wiki @

Morphia Query official documentation

MongoDB $in documentation

MongoDB $nin documentation


Leave a Reply

Your email address will not be published. Required fields are marked *