2017-02-21 101 views
0

我試圖使用Java驅動程序使用聚合框架來轉換MongoDb查詢。我在這裏幫助創建了查詢How to apply filter for output of aggregation framework of Mongo Db?將聚合查詢MongoDb轉換爲BasicDbObject Java

下面是示例彙總查詢:

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:[{$平均: 「$ customerReviews」} ,7]}。我認爲它應該像gtQuery.put(avgQuery,new BasicDbObject(「$ gt」,7)),但顯然不能在put()函數中放入String以外的東西。

順便說一句,我不確定是否只能使用BasicDbObject完成$ redact,或者我需要類似使用Spring Mongo的Mongo spring query where two fields are equal之類的東西。希望有人能幫助我完成整個查詢。

回答

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