【问题标题】:MongoDb comparing two fields in same collection, in javaMongoDb比较同一集合中的两个字段,在java中
【发布时间】:2019-07-30 11:03:31
【问题描述】:

如何使用 Mongo-DB java 驱动比较同一集合中的两个字段?我需要分批获取数据,然后在适当过滤后处理它们。下面是我正在尝试的那种代码。

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"}}]});

【问题讨论】:

标签: java spring mongodb mongodb-query bson


【解决方案1】:

有很多方法可以解决您的问题
首先你可以使用$where 来做到这一点

 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");

其次你可以使用$expr

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

您还可以将 $redact$cond 与聚合一起使用

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

它可能对你有帮助!

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多