MongoDB Java driver 3.x: How to pass allowDiskUse=true to aggregate() method?

前端 未结 1 1542
Happy的楠姐
Happy的楠姐 2020-12-17 19:50

I\'m using mongo-java-driver 3.0.2.

I have a method that uses MongoCollection.aggregate(List pipeline) to sort and limit:

1条回答
  •  攒了一身酷
    2020-12-17 20:42

    This still works on the 3.0.3 driver:

        MongoClient client = new MongoClient(new ServerAddress("127.0.0.1", 27017));
    
        DB test = client.getDB("test");
    
        DBCollection sample = test.getCollection("sample");
    
        List aggregationQuery = Arrays.asList(
                new BasicDBObject("$sort",new BasicDBObject("score",-1)),
                new BasicDBObject("$limit",1)
        );
    
        System.out.println(aggregationQuery);
    
        Cursor aggregateOutput = sample.aggregate(
                aggregationQuery,
                AggregationOptions.builder()
                        .allowDiskUse(true)
                        .build()
        );
    
        while ( aggregateOutput.hasNext() ) {
            DBObject doc = aggregateOutput.next();
            System.out.println(doc);
        }
    

    Of course you can also use newer classes as well:

        MongoClient client = new MongoClient(new ServerAddress("192.168.2.4", 27017));
    
        MongoDatabase db = client.getDatabase("test");
    
        MongoCollection collection = db.getCollection("sample");
    
        AggregateIterable result = collection.aggregate(Arrays.asList(
                new BasicDBObject("$sort", new BasicDBObject("score", -1)),
                new BasicDBObject("$limit", 1)
        )).allowDiskUse(true);
    
        MongoCursor cursor = result.iterator();
    
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            System.out.println(doc);
        }
    

    So .aggregate() on MongoCollection returns an AggregateIterable class instance, which has an .allowDiskuse() method as well as others to set aggregation options.

    0 讨论(0)
提交回复
热议问题