简体   繁体   中英

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.

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 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM