How to make a numerical comparison when using morphia to execute a $ elemMatch request

My document has the following structure:

{ "scores": [{ "scoreTitle": "environment", "scoreValue": 3, "scoreDescribe": "good" }, { "scoreTitle": "service", "scoreValue": 3, "scoreDescribe": "good" }, { "scoreTitle": "taste", "scoreValue": 4, "scoreDescribe": "good" }] } 

In the mongo shell, I can use the following query to find a document that has a rating whose heading is "medium" and the value is greater than 2.

 db.reviews.find({"scores":{"$elemMatch":{"scoreValue":{"$gt":2},"scoreTitle":"environment"}}}) 

Now I want to request a document using morphia, from api doc, the 'elem' operator is supported in the fiter method, and an additional request criteria object is required, for example, a request for a document that has a rating, title is β€œenvironment”, and description is β€œgood” :

 Score score = new Score();// the criteria object, only support comparisons of equality score.setScoreTitle("environment"); // title should be environment score.setScoreDescribe("good"); // describe should be good Query q = ds.createQuery(Review.class).filter("scores elem", score); 

My question is: how can I make a numerical comparison in the query criteria, that is, how can I make a query that has the same effect as a copy of the mongo shell.

+6
source share
2 answers

I think you can try

 ds.createQuery(Review.class). filter("scores.scoreValue >=", 2). filter("scores.scoreTitle", "environment"). retrievedFields(true, "scores.$") 
+1
source

Morphia's code base has a large number of tests, you can see examples of several different ways to make comparison operators here:

http://code.google.com/p/morphia/source/browse/trunk/morphia/src/test/java/com/google/code/morphia/TestQuery.java

0
source

Source: https://habr.com/ru/post/944839/


All Articles