Morphia query example : equal(), notEqual() and hasThisOne()

Morphia query example : equal(), notEqual() and hasThisOne()

When querying using Morphia’s fluent API you will often need to select entities by using equality comparison. This is pretty much the same as using the WHERE x=y clause in SQL databases.

equal() and hasThisOne() correspond to the $eq operator in mongoDB. They both work exactly the same way although you might prefer to use hasThisOne() on array fields for code readbility.

notEqual() corresponds to the  $ne mongoDB operator and works the opposite way by testing for field inequality.  Note that when the tested entity field is an array or collection, the query will return entities where at least one entry in the array matches the passed value.

 

equal(), notEqual() and hasThisOne() example :

 

 

output :

User where login equal() Foo : login = Foo – carBrand = audi
——————————
sportsCarsLovers with hasThisOne() :
Foo
Bar
——————————
sportsCarsLovers with equal() :
Foo
Bar
——————————
nonFerrariOwners notEqual() :
Foo
TheBest
Bob
——————————
nonFerrariOwnersNonAudiOwners multiple notEqual() combined
TheBest
Bob
——————————

 

Note : when chaining queries, the default behaviour of the API is to combine them with an AND clause. So in the last example above you could read the last query as SELECT users where firstName equals “Alex” AND lastName not equals “Foobar” .

 

References

Morphia documentation wiki @ gtihub.com

Morphia Query official documentation

MongoDB $eq documentation

MongoDB $ne documentation

 

 

 

Leave a Reply

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