如何使用java驱动程序复制mongodb集合(v3.4)

时间:2017-02-15 13:04:25

标签: java mongodb

我正在尝试将现有集合复制到同一数据库中的新集合,模拟在shell中运行db.source.aggregate({"$out":"target"});的行为。

在旧版本的mongodb和java驱动程序上,可以这样做(如here所示):

// set up pipeline
List<DBObject> ops = new ArrayList<DBObject>();
ops.add(new BasicDBObject("$out", "target")); // writes to collection "target"

// run it
MongoClient client = new MongoClient("host");
DBCollection source = client.getDB("db").getCollection("source")
source.aggregate(ops);

但是因为mongo 3.0.0,the writers are moving away from DBCollectionMongoCollection以及其他不具有相同功能的内容,特别是.aggregate(List<DBObject>)

我尝试了以下选项,但没有任何效果:

List<Bson> ops = new ArrayList<>();
ops.add(new BasicDBObject("$out", "target"));
//OR
ops.add(new Document("$out", "target")); //not at the same time as above

MongoClient client = new MongoClient("host");
MongoCollection source = client.getDatabase("db").getCollection("source");
source.aggregate(ops);

可悲的是,我不清楚总体操作是否足以解决这个问题。

使用java驱动程序和mongo 3.4有没有类似的方法呢? 有没有其他方法可以导致复制服务器端?

由于

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

MongoClient client = new MongoClient("host");
MongoCollection source = client.getDatabase("db").getCollection("source");    
source.aggregate(Arrays.asList(out("<OutputcollectionName>")));

使用以下import语句:

 import static com.mongodb.client.model.Aggregates.*;

答案 1 :(得分:0)

添加应该没有noOps块的.toCollection()..