Sandro
Sandro

Reputation: 71

Compare two fields in the document with criteria in mongodb

I would like to understand how do I compare two fields in the document. Has anyone ever needed to do this type of comparison? I'm using the criteria.

criteria.add(Criteria.where("this.campoC == this.campoD"));

Query query = new Query();
List<Criteria> criteria = new ArrayList<>();

criteria.add(Criteria.where("campoA").is(123));
criteria.add(Criteria.where("campoB").is("N"));
criteria.add(Criteria.where("this.campoC == this.campoD")); // <---- How do you compare two fields???
    
query.addCriteria(new Criteria().andOperator(criteria.toArray(new Criteria[criteria.size()]))).limit(1);
return query;

Upvotes: 0

Views: 479

Answers (1)

Ahmad Shakil
Ahmad Shakil

Reputation: 11

Try this one

Criteria matchCriteria = new Criteria() {
     @Override
     public Document getCriteriaObject() {
       Document doc = new Document();
       doc.put( "$where", "this.campoC == this.campoD");
         return doc;
       }
  };

criteria.add(matchCriteria ); 

Upvotes: 1

Related Questions