如何使用 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"}}]});
最佳答案
有很多方法可以解决您的问题
首先,您可以使用 $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"
]
}
也许对你有帮助!
关于java - MongoDb 在java中比较同一集合中的两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57270161/