How to write MongoTemplate Query and Criteria for a complex Document structure?

Kishor .M picture Kishor .M · Nov 28, 2016 · Viewed 11.8k times · Source

I am new to MongoTemplate. I want to define a org.springframework.data.mongodb.core.query.Query and org.springframework.data.mongodb.core.query.Criteria to fetch the data from a collection which has a complex document structure. This is the document

{
"_id" : {
    "SId" : "ANBS",
    "AssetId" : "ANBS_BS21",
    "ST" : NumberLong(1479114000) //StartDate
},
"ET" : NumberLong(1479117599) //EndDate,
"TS" : [ 
    NumberLong(1479114000), 
    NumberLong(1479114600), 
    NumberLong(1479115200), 
    NumberLong(1479115800), 
    NumberLong(1479116400), 
    NumberLong(1479117000)
],
"Tags" : {
    "ActivePower" : {            
        "Avg" : [ 
            16427.575, 
            16991.01, 
            16708.2016666667, 
            16488.335, 
            17230.1933333333, 
            15996.9783333333
        ]
    },
    "WindSpeed" : {            
        "Avg" : [ 
            64.4266666666667, 
            60.8583333333333, 
            65.275, 
            62.8766666666667, 
            63.2166666666667, 
            63.14
        ]
    }
}

I want to fetch all the documents for a given TimeRange(StartTime and EndTime), WHERE AssetId=? AND startTime >= ST AND endTime <= ET.

Can anybody help me with this problem? I dont want the mongo query, but I want the MongoTemplate based query and criteria. Thanks in advance.

Answer

Kishor .M picture Kishor .M · Nov 29, 2016

I got a solution, it was very simple. Posting this answer so that it can help someone else.

Query query = new Query(Criteria 
            .where("_id.SId").is(siteId)
            .and("_id.AssetId").is(assetId)
            .and("_id.ST").gte(startTimeRange)
            .and("ET").lte(endTimeRange));
return mongoTemplate.find(query, MyCollection.class, "mycollection");