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

标签 java mongodb

我正在尝试将现有集合复制到同一数据库中的新集合,模拟运行 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 DBCollection并进入MongoCollection和其他不具有相同功能的,特别是 .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来做到这一点?
还有其他方法会导致服务器端复制吗?

谢谢

最佳答案

你可以试试这个:

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

使用以下导入语句:

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

关于java - 如何使用 java 驱动程序复制 mongodb 集合 (v3.4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42250215/

相关文章:

mongodb - 在命令提示符下将git与mongodb一起使用时出现问题

java - 如何安装\导入ebay sdk

java - java中的Unix命令

java - 在 Spring Boot 中使用 @EnableWebFluxSecurity 时出错

mongodb - 用于部分匹配和不区分大小写查询的 Mongo Atlas 搜索索引

java - mongo shell中如何获取子文档记录

java.exe 未被识别为内部或外部命令

java - 在列表的序列化中包含具有数组索引的字段

node.js - 类型错误 : Cannot use 'in' operator to search for '_id' in male

mongodb - 在 MongoDB 中存储非常大的文档