Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make numeric comparison when using morphia to perform an $elemMatch query

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 mongo shell, I can use the following query to find the document which has a score whose title is 'environment' and value is greater than 2.

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

Now I want to query the document using morphia, from the api doc, the 'elem' operator is supported in the fiter method, and an additional query criteria object is required, for example, query for document that has a score whose title is "environment" and describe 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 numeric comparison in the query criteria, that is to say, how can I make a query that has the same effect as the mongo shell counterpart.

like image 938
ltebean Avatar asked May 13 '13 03:05

ltebean


1 Answers

I guess you can try

ds.createQuery(Review.class).
  filter("scores.scoreValue >=", 2).
  filter("scores.scoreTitle", "environment").
  retrievedFields(true, "scores.$")
like image 167
arthurfnsc Avatar answered Nov 06 '22 16:11

arthurfnsc