gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:39:18 25 4
gpt4 key购买 nike

我正在尝试将现有集合复制到同一数据库中的新集合,模拟运行 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com