vashishth
vashishth

Reputation: 3400

Spring MongoDB BasicQuery not working with projection

I have following BasicQuery

BasicQuery query2 = new BasicQuery("{status:{$in:['APPROVED','NEW','OPEN']}},{siteId:1,_id:0}");

Where BasicQuery is a class from SpringData mongoDb org.springframework.data.mongodb.core.query.BasicQuery. While doing the debug the above query get compiled into

Query: { "status" : { "$in" : [ "APPROVED" , "NEW" , "OPEN"]}}, Fields: null, Sort: { }

But it should have been compiled as below

Query: { "status" : { "$in" : [ "APPROVED" , "OPEN" , "NEW"]}}, Fields: { "siteId" : 1 , "_id" : 0}, Sort: null

If you notice, fields are still missing into compiled BasicQuery. Please help how i can have project in BasicQuery. I can have projection by using Query as below.

Query query = new Query();
        query.addCriteria(Criteria.where(STATUS).in(validStatus));
        query.fields().include("siteId").exclude("_id");

My query is how i can achieve the same using BasicQuery.

Upvotes: 0

Views: 1996

Answers (2)

SagitSri
SagitSri

Reputation: 521

BasicQuery query = new BasicQuery("{ $and: [{ studentId: { $in: "+studentIds+" } }, { status: { $ne:  '"+studStatus+"'} }] }");

studentIds is an array and studStatus is a string! Thanks to vashishth

Upvotes: 0

vashishth
vashishth

Reputation: 3400

I guess i got the answer. Instead of using single string argument constructor of BasicQuery we need to use two String argument basic query as follow.

BasicQuery query2 = new BasicQuery("{status:{$in:['APPROVED','NEW','OPEN']}}","{siteId:1,_id:0}");

Above will compile into following query

Query: { "status" : { "$in" : [ "APPROVED" , "OPEN" , "NEW"]}}, Fields: { "siteId" : 1 , "_id" : 0}, Sort: null

Upvotes: 3

Related Questions