Sthita
Sthita

Reputation: 1782

How to use SpEL expression on Spring Data Mongodb?

I am not able to figure-out how to use SpEL expression to my existing query and document for a newly introduced field.

Example :

@Document(collection = "abc")
public class Abc {

 private boolean deleted;
 public boolean isDeleted() {
  return deleted;
 }

 public void setDeleted(boolean deleted) {
  this.deleted = deleted;
 }

}

I am already using Spring Data Mongodb

@Repository
public interface AbcRepository extends MongoRepository < Abc, String > {

 Abc findAllByDeleted(boolean deleted);

}

Note: I have almost 1000+ documents on abc collection.

I wanted to introduce new field for example status on my collection and my query is going to change and it will not return me anything because the new field is not exists with old data , how do I handle this scenario ? I don't want to do data-patch. So i found we can use exists from spring data SpEL expression.

https://docs.spring.io/spring-data/mongodb/docs/2.1.0.M3/reference/html/#mongodb.repositories.queries.json-spel

Here are my changes :

@Document(collection = "abc")
public class Abc {
...
...

private boolean status;
 public boolean isStatus() {
  return status;
 }

 public void setStatus(boolean status) {
  this.status = status;
 }
}

and my query changes to

//Tried this but throwing exception
@Query("{'status' : {$exists :false}}")
Abc findAllByDeletedAndStatus(boolean deleted, boolean status);

How can use SpEL Expressions to check if status field is exists and apply the parameter passed from caller?

Upvotes: 1

Views: 3784

Answers (1)

Than
Than

Reputation: 446

I am not sure to fully understand your request, but see bellow a bit of help.

Assuming Abc has deleted and status attributes :

@Query("{ $and :[" +
          "?#{ { 'deleted' : [0] } }," +
          "?#{ { 'status' : [0] } }" +
         "]}")
  Abc findAllByDeletedAndStatus(boolean deleted, boolean status);

If your params are optional, you could use this way (which is very useful in case of optionals filters):

  @Query("{ $and :[" +
          "?#{ [0] == null ? { $where : 'true'} : { 'deleted' : [0] } }," +
          "?#{ [1] == null ? { $where : 'true'} : { 'status' : [1] } }" +
       "]}")
  Abc findAllByDeletedAndStatus(boolean deleted, boolean status);

Upvotes: 2

Related Questions