Muralidhar
Muralidhar

Reputation: 143

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,

Upvotes: 4

Views: 2948

Answers (2)

s7vr
s7vr

Reputation: 75914

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);

Upvotes: 1

pvpkiran
pvpkiran

Reputation: 27018

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());

Upvotes: 1

Related Questions