How to create a criteria in Grails with a conjunction(and) of two disjunctions(or) using MongoDB?

StackOverflow https://stackoverflow.com/questions/16525519

문제

I'm trying to get all the activities from a user or its teams also filtered by some types if some properties are set.

This is what I have right now:

Activity.withCriteria{
    and{
        or {
            eq 'user',myUser
            "in" 'team',userTeams
        }
        and{
            if (showA || showB || showC){
                or{
                    if (showA){
                        "in" "a", myAList
                    }
                    if (showB){
                        "in" "b", myBList
                    }
                    if (showC){
                        "in" "c",myCList
                    }
                }
            }
        }
    }
    order "date","desc"
    maxResults maxElements
}

Executing that, what I get it's the OR of user and team block and the showA, showB, showC block instead of the AND of those two blocks.

I'm using grails 2.2.1 (also using MongoDB GORM 1.2.0 without Hibernate)

EDIT:

I have been able to see the query that's sent to MongoDB and it's not doing the first part of the criteria. This is the query that's being passed to MongoDB:

query: { query: { $or: [ { a: { $in: [ "5191e2c7c6c36183687df8b6", "5191e2c7c6c36183687df8b7", "5191e2c7c6c36183687df8b8" ] } }, { b: { $in: [ "5191e2c7c6c36183687df8b9", "5191e2c7c6c36183687df8ba", "5191e2c7c6c36183687df8bb" ] } }, { c: { $in: [ "5191e2c7c6c36183687df8b5" ] } } ] }, orderby: { date: -1 } }  ntoreturn: 10 ntoskip: 0

EDIT: I have just seen that a JIRA has already been raised and it seems that's a MongoDB plugin problem... http://jira.grails.org/browse/GPMONGODB-296

도움이 되었습니까?

해결책 2

With the new version of Mongo for Grails this has been fixed, so now it's working with version 1.3.0.

http://grails.org/plugin/mongodb

다른 팁

You can think in your criteria in a SQL perspective.

and ((user = 'myUserValue'
 or   team in (...))
and(a in (...)
  or b in (...)
  or c in (...)))

So your or is applied to user and team, but I think you want something like:

or {
  and {
    eq 'user',myUser
    "in" 'team',userTeams
  }
  and{
    if (showA || showB || showC){
      or{
        if (showA){
          "in" "a", myAList
        }
        if (showB){
          "in" "b", myBList
        }
        if (showC){
          "in" "c",myCList
        }
      }
    }
  }
}

So the key here is that the block you declare is applied to what you have inside.

EDIT:

A good tip to inspect a criteria is to enable the output of sql's generated by Hibernate. This can be done in DataSource.groovy

dataSource {
  logSql = true
}

hibernate {
  format_sql = true
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top