Spring MongoDB Data elemMatch Simple

萝らか妹 提交于 2020-04-11 06:15:10

问题


{ _id: 1, results: [ "tokyo", "japan" ] }
{ _id: 2, results: [ "sydney", "australia" ] }




db.scores.find(
   { results: { $elemMatch: { $regex: *some regex* } } }
)

How do you convert this simple elemMatch example using spring mongodb data Query Criteria?

If the array contains object I can do it this way

Criteria criteria = 
   Criteria.where("results").
   elemMatch(
      Criteria.where("field").is("tokyo")
   );

But in my question, I dont have the "field"

Update:

I thought the Veeram's answer was going to work after trying it out

Criteria criteria = 
   Criteria.where("results").
   elemMatch(
      new Criteria().is("tokyo")
   );

It does not return anything. Am I missing something?

When i inspect the query object, it states the following:

Query: { "setOfKeys" : { "$elemMatch" : { }}}, Fields: null, Sort: null

On the other hand, If i modify the criteria using Criteria.where("field") like above,

Query: { "setOfKeys" : { "$elemMatch" : { "field" : "tokyo"}}}, Fields: null, Sort: null

I'm getting something but that's not how my data was structured, results is an array of strings not objects. I actually need to use regex, for simplicity , the above example is using .is


回答1:


You can try below query.

Criteria criteria = Criteria.where("results").elemMatch(new Criteria().gte(80).lt(85));


来源:https://stackoverflow.com/questions/52267601/spring-mongodb-data-elemmatch-simple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!