Search code examples
javaspringmongodbmongodb-querybson

MongoDb comparing two fields in same collection, in java


How do I compare two fields in the same collection using Mongo-DB java driver? I need to fetch data in batches and then work on them after proper filtering. Below is the sort of code that I was trying.

MongoCollection<Document> collection = getCollection();
FindIterable<Document> documents = collection.find(
    or(
       lt(field1, 0),
       gt(field2, field3)
    )
)
.projection(Projections.fields(Projections.include(field1)))
    .sort(Sorts.ascending(field1))
    .batchSize(1000).noCursorTimeout(true);

documents.forEach((Block<Document>) document ->{
 // remaining code
}


//Mongo Query

db.example.find( { $or:[{"field1":{$lt:0}}, {"field2":{$gt:"$field3"}}]});


Solution

  • there are many way to deal with your problem
    firstly you can use $where to do this

     db.ct_work.find(
    { $or:[{"field1":{$lt:0}},
        {"$where":"this.field2 >= this.field3"}]}) 
    
    ## in java  you  do with  Filters.where  or  create  a  DBObject
    
    Filters.where("this.a > this.b") 
    
    DBObject obj = new BasicDBObject();
    obj.put("$where", "this.subNum >= this.stuNum");
    

    secondly you can use $expr

    ## like 
    db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )
    

    you can also use with aggregate with $redact and $cond

    $match:{},
     $redact: {
                    "$cond": [{
                            "$gt": ["$firstfield", "$secondfiled"}]
                        },
                         "$$KEEP", "$$PRUNE"
                    ]
                }
    
    

    it may helps to you !