我尝试使用Java驱动程序使用聚合框架转换MongoDb查询。我在这里How to apply filter for output of aggregation framework of Mongo Db?帮助创建了查询。
以下是示例聚合查询:
db.movies.aggregate(
[{
$redact: {
$cond: {
if: {$gt: [{ $avg: "$customerReviews"}, 7 ] },
then: "$$KEEP",
else: "$$PRUNE"
}
}
},
{$skip:1},
{$limit:2}
]
);
我开始时:
BasicDBObject avgQuery = new BasicDBObject("$avg", "$customerReviews");
但无法弄清楚如何执行{$ gt:[{$ avg:" $ customerReviews"},7]}。我认为它应该像gtQuery.put(avgQuery,new BasicDbObject(" $ gt",7)),但显然不能在put()函数中添加除String以外的东西。
顺便说一下,我不确定是否只能使用BasicDbObject来完成$ redact,或者我需要使用Spring Mongo的Mongo spring query where two fields are equal之类的东西。希望有人可以帮助我完成整个查询。
答案 0 :(得分:2)
BasicDBObject
是旧的2.x mongo版本类。使用较新的3.x api类。
我没有看到任何助手类在java驱动程序中创建redact
管道。
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("dbname");
MongoCollection<Document> collection = database.getCollection("dbcollection");
List<Document> results = collection.aggregate(Arrays.asList(
new Document("$redact", new Document("$cond",
Arrays.asList(new Document("$gt",
Arrays.asList(new Document("$avg", "$customerReviews"), 7)),
"$$KEEP", "$$PRUNE"))),
Aggregates.skip(1),
Aggregates.limit(2)
)).into(new ArrayList<>());
或者你可以使用
String redact = "{\n" +
" $redact: {\n" +
" $cond: {\n" +
" if: {$gt: [{ $avg: \"$customerReviews\"}, 7 ] },\n" +
" then: \"$$KEEP\",\n" +
" else: \"$$PRUNE\"\n" +
" }\n" +
" }\n" +
"}";
List<Document> results = collection.aggregate(Arrays.asList(
Document.parse(redact),
Aggregates.skip(1),
Aggregates.limit(2)
)).into(new ArrayList<>());