skip to Main Content

my data strucutre look like this:

Teams:
{ name:"team1",
  users:[
     {
     age:45,
     licence:true
     },
     {
     age:70,
     licence:false
     }
 ]
},
..other teams..

I want to return teams with at least one person = 70years old who has licence.
My current code looks like this:

criteria = Criteria.where("user.age").(70).and("user.licence").is(true)
Query q = new Query(criteria);
... perform q ...

The problem is that this kind of criteria recognize if there exist somone = 70 AND somone with licence (not somone with licence and 70 at the same time) so in my case it would return true even though its not. Im not sure how can i perform this kind of (simple) query. I was looking for it in documentation but no successes 🙁

2

Answers


  1. Use addCriteria(…) method

    In your case :

    val query = Query(
                    Criteria.where("users.age").isEqualTo(70)
            ).addCriteria(
                    Criteria.where("users.licence").isEqualTo(false)
            )
    
    //Then perform query
    
    

    Sorry for it not being in plain Java. But shouldn’t be hard to get turn it into it.

    Login or Signup to reply.
  2. Use the $elemMatch operator to match multiple fields of a subdocument in a subdocument array.

    Raw query

    {
      "users": {
        "$elemMatch": {
          "age": 70,
          "licence": true
        }
      }
    }
    

    Spring criteria

          Criteria.where("users")
            .elemMatch(Criteria.where("age").is(70).and("licence").is(true));
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search