Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify field projections in spring mongo db query

{
    "_id":"1",
    "company":"ABCD",
    "Address":{
    "Location":"XYZ"
    },
    "empName":[{
    "ID":1,
    "Name":"test1"
    },
    "ID":2,
    "Name":"test2"
    },
    "ID":3,
    "Name":"test3"
    }]
}

am using mongoTemplate query,

Criteria findCriteria1 = Criteria.where("_id").is("1");
Criteria find2Criteria = Criteria.where("empName").elemMatch(Criteria.where("ID").is(1));
BasicQuery basicQuery = new BasicQuery(findCriteria1.getCriteriaObject(), find2Criteria.getCriteriaObject());
mongoTemplate.findOne(basicQuery, ClassName.class);

but my result as below with other fields displayed null.

{
    "_id":"1",
    "company":null,
    "Address":null,
    "empName":[{
    "ID":1,
    "Name":"test1"
    }]
}

my expected result should be like this,

"_id":"1",
"company":"ABCD",
"Address":{
"Location":"XYZ"
},
"empName":[{
"ID":1,
"Name":"test1"
}]

Can you please help me to fix this issue.

Thanks in advance,

like image 994
Muralidhar Avatar asked Sep 05 '25 09:09

Muralidhar


2 Answers

Do Read the documentation for Criteria and BasicQuery.

The second argument in this

BasicQuery basicQuery = new BasicQuery(findCriteria1.getCriteriaObject(), find2Criteria.getCriteriaObject());  

is basically a projection. i.e. you are telling the driver to fetch only the fields mentioned in those. Hence other fields are not fetched and hence null.

If you want to fetch all fields this is what you should do in your case

    Criteria findCriteria1 = Criteria.where("_id").is("1");  
    Criteria find2Criteria = Criteria.where("empName").elemMatch(Criteria.where("ID").is(1));  
    BasicQuery basicQuery = new BasicQuery(findCriteria1.andOperator(find2Criteria).getCriteriaObject());
like image 168
pvpkiran Avatar answered Sep 09 '25 01:09

pvpkiran


You can use below code.

You can chain the fields you require in the Field class.

Criteria criteria = Criteria.where("_id").is("1");
Query query = new Query(criteria);
query.fields().elemMatch("empName", Criteria.where("ID").is(1)).include("company");
mongoTemplate.findOne(query , ClassName.class);
like image 41
s7vr Avatar answered Sep 09 '25 02:09

s7vr