如何使用Java Mongodb的AggregateToCollectionOperation类?

时间:2016-04-12 00:17:21

标签: java mongodb

我有这个mongo shell命令,我需要转换为Java代码。 看起来驱动程序API经常更改,以至于我在网上看到的任何示例都不使用此方法。我正在使用最新的3.2.4版本的驱动程序。

db.ff1987_2gram.aggregate([ 
   { 
       $group: { 
           _id : { 
               "cw1" : "$cw1", 
               "target" : "$target"
           }, 
           "count" : {"$sum" : 1 }  
       }
  },
  {$out : "ff1987_2gram_c"} 
], { allowDiskUse:true} )

https://api.mongodb.org/java/3.2/com/mongodb/operation/AggregateToCollectionOperation.html有我想做的事。但它的execute方法采用WriteBinding接口对象。这是由ClusterBinding,SingleServerBinding实现的。但我没有使用其中任何一个。我使用新的MongoClient类连接到数据库。

1 个答案:

答案 0 :(得分:0)

虽然这不能回答我原来的问题,但以下是一个不错的解决方法。我想这是一个已弃用的类,因为引入了MongoClient。

而不是使用AggregateToCollectionOperation,使用带有$ out的其中一个阶段的正常聚合操作,就像在mongo shell命令中一样。但请记住,除非您迭代返回的iterable,否则该命令实际上并未执行。 (它可能足以在第一个元素之后中断。在我检查之后会更新)。以下是一个例子。

List<Document> pipeline = new ArrayList<>();
...
Document group = new Document("$group", groupargs);
pipeline.add(group);
...
//Relevant line
pipeline.add(new Document("$out", collectionname));
AggregateIterable<Document> docs = db.getCollection(collection).aggregate(pipeline).allowDiskUse(true);
for (Document d : docs) {}