How do you make a distinct query on GORM subdocument fields?

887 Views Asked by At

Given Grails 2.3.8 and Mongo 2.6.0, and this (simplified) domain class:

db.account.findOne()
{
    "name":"Test Account",
    "customer": {
        "state": "CA"
    }
}

where every account has a customer subdocument with a "state" string. To get a list of all states across all customers, I would think to do something like this:

def states = Account.createCriteria().list {
    projections{
        distinct("customer.state")
    }
}

But it doesn't work because of an existing bug - https://jira.grails.org/browse/GPMONGODB-397

Is there a workaround?

I can do this: Account.collection.distinct("customer.state") but is there a more Grails-ish way to do it?

1

There are 1 best solutions below

0
On

You can use "Criteria.DISTINCT_ROOT_ENTITY" for DISTINCT record.

def users = Account..withCriteria {
        resultTransformer Criteria.DISTINCT_ROOT_ENTITY
}