7
{ _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

user1955934
  • 3,185
  • 5
  • 42
  • 68

2 Answers2

2

You can try below query.

Criteria criteria = Criteria.where("results").elemMatch(new Criteria().gte(80).lt(85));
s7vr
  • 73,656
  • 11
  • 106
  • 127
-1

Try this

Criteria criteria = Criteria.where("results").regex(".*tokyo.*","i");
O.Ndiaye
  • 1
  • 1
  • 2
    Welcome to Stack Overflow, and thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts. That's especially important when there's already an accepted answer that's been validated by the community. Under what conditions might your approach be preferred? Are you taking advantage of new capabilities? – Jeremy Caney Aug 13 '21 at 20:00