Viraj
Viraj

Reputation: 5411

MongoDB Spring Data Criteria Not operator

I have following code to search in mongo db using spring data mongodb ( version 1.2.3.RELEASE)

Criteria searchCriteria = Criteria.where("NAME").is("TestName")
        .and("ID").is("TestID").not().and("Age").is("23");

I got following query ( without not operator )

Query: { "NAME" : "TestName" , "ID" : "TestID", "Age" : "23" }

I was expecting following query

Query: { "NAME" : "TestName" , "$not" : { "ID" : "TestID"}, "Age" : "23" }

What am i doing wrong ? Any help is greatly appreciated. Thanks

Upvotes: 14

Views: 28007

Answers (3)

Virendra khade
Virendra khade

Reputation: 97

If you have multiple items then you can use below query for mongo andOperator(Criteria.where(name).nin(ids))

Upvotes: 0

Viraj
Viraj

Reputation: 5411

I used 'ne' instead.

 Criteria searchCriteria = Criteria.where("NAME").is("TestName").and("ID").ne("TestID").and("Age").is("23");

Mongo db 'not' is a logical operator. http://docs.mongodb.org/manual/reference/operator/query/not/

Upvotes: 21

Gabriel Petrovay
Gabriel Petrovay

Reputation: 21944

According to the documentation the not() is affecting the clause directly following. That is the .and("Age").is("23"). But you probably have to put it before the is.

Criteria searchCriteria = Criteria.where("NAME").is("TestName").and("ID").not().is("TestID").and("Age").is("23");

If this is not working, try using the andOperator and the not().where("ID") construct.

Upvotes: 4

Related Questions