Search code examples
mongodbgrailsgrails-ormcriteria

Grails-Mongo Check Contains in Domain's List Criteria Query


I'm using grails 3.3.5 with GORM Version 6.1.9

In my application I've created the domain as follows..

class Camera {
     String cameraId
     List<String> typesInclude

   static constraints = {
      typesInclude nullable: false
   }
}

Now I've added some records in the Camera Colletions.

db.camera.find().pretty()
{
    "_id" : NumberLong(1),
    "version" : NumberLong(0),
    "typesInclude" : [
        "T1"
    ],
    "cameraId" : "cam1"
}
{
    "_id" : NumberLong(2),
    "version" : NumberLong(0),
    "typesInclude" : [
        "T2"
    ],
    "cameraId" : "cam2",
}
{
    "_id" : NumberLong(3),
    "version" : NumberLong(0),
    "typesInclude" : [
        "T2",
        "T3"
    ],
    "cameraId" : "cam3",
}

Now when I'm trying to get Camera By type like T2. I'm unable to get results using the following function..

def getCameraListByType(String type){
    def cameraInstanceList = Camera.createCriteria().list {
         ilike("typesInclude","%${type}%")
    }
    return cameraInstanceList
}

Any help would be appreciated.


Solution

  • I wouldn't use criteria queries with mongo, as they barely reflect document-oriented paradigm.

    Use the native queries instead, as they are way more powerful:

    def getCameraListByType(String type){
        Camera.collection.find( [ typesInclude:[ $regex:/$type/, $options:'i' ] ] ).collect{ it as Camera }
    }