jeudi 13 août 2015

Spring Mongo "elemMatch" - get other fields included in the result along with specified array elements match

I am working on a web application using Spring + Jersey + Mongo. I am using elemMatch from spring mongo for some specific result.

Here is my class that will be mapped with the output of the mongo query.

public class ABC {
    private String id;

    private String dId;

    private String lId;

    private String hId;

    private String pId;

    private List<GeneralData> generalRecords;

    private List<String> fhistory;

    private List<String> mhistory;

    private List<String> specialNotes;
}

public class GeneralData {
    private Object data;

    private HistoryFilter dataType;
}

Now, this is how my data looks like in mongo :

{
    "_id" : ObjectId("55ccda7fe4b03cc159c2ce17"),
    "_class" : "com.dpdocter.collections.HistoryCollection",
    "dId" : "5525ef96e4b077dfc168369b",
    "lId" : "5525ef96e4b077dfc16836a1",
    "hId : "5525ef96e4b077dfc16836a0",
    "pId" : "55ccd9f1e4b03cc159c2ce0b",
    "generalRecords" : [ 
        {
            "data" : "55ccdde7e4b03cc159c2ce18",
            "dataType" : "REPORTS"
        }, 
        {
            "data" : "55ccda63e4b03cc159c2ce14",
            "dataType" : "CLINICAL_NOTES"
        }
    ]
}

I want record based on dId, lId, hId, pId along with elemMatch on generalRecords for a specific dataType (say REPORTS). And, below is my criteria code to do that.

Criteria matchCriteria = Criteria.where("dId").is(dId).and("lId").is(lId).and("hId").is(hId).and("pId").is(pId).and("generalRecords.dataType").is("REPORTS");
Criteria elementMatchCriteria = Criteria.where("generalRecords").elemMatch(Criteria.where("dataType").is("REPORTS"))

BasicQuery query = new BasicQuery(matchCriteria.getCriteriaObject(), elementMatchCriteria.getCriteriaObject());

ABC abc = mongoOperations.findOne(query, ABC.class);

Result of the above

ABC [id=55ccda7fe4b03cc159c2ce17, dId=null, lId=null, hId=null, pId=null, generalRecords=[GeneralData [data=55ccdde7e4b03cc159c2ce18, dataType=REPORTS]], fhistory=null, mhistory=null, specialNotes=null]

generalRecords is just perfect and as desired, but I just want to include dId, lId, hId, pId, fHistory, mHistory, and specialNotes also. I have already tried :

query.fields().include('fieldName')

also, some other weird query combos, but nothing helps. Can anyone suggest something.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire