soso
soso

Reputation: 401

Query an embedded list of a model

I have a model that i embedded on another model :

My first model looks like this

class Location {

    static mapWith = "mongo"

    String name
    String symbol

    List<LocationType> locationType

    static embedded = ['locationType']
}

second model (this is embedded on the Location model a list of LocationType):

class LocationType {

    static mapWith = "mongo"

    List<LocaleEnum> locale
    Date dateCreated    
}

On my mongodb database I have a document that has a list of the embedded LocationType model the document is:

{
    "_id" : NumberLong(11),
    "name" : "12",
    "locationType" : [ 
        {
            "dateCreated" : ISODate("2015-03-30T08:59:44.296Z"),
            "locale" : [ 
                "en", 
                "am"
            ]
        }, 
        {
            "dateCreated" : ISODate("2015-03-30T09:50:50.649Z"),
            "locale" : [ 
                "en"
            ]
        }, 
        {
            "dateCreated" : ISODate("2015-03-31T07:49:36.998Z"),
            "locale" : [ 
                "om"
            ]
        }
    ],
    "version" : NumberLong(2)
}

I want to query this from my service document by dateCreated of the embedded model and get the recently added locationType

Upvotes: 1

Views: 42

Answers (1)

Alexander Suraphel
Alexander Suraphel

Reputation: 10613

Just do:

LocationType recentlyAddedLocType = locationObj.locationType.max { it.dateCreated } 

Upvotes: 1

Related Questions