MongoDB - 在java中复制集合而不循环所有项目

pri*_*lia 3 java collections mongodb

有没有办法将所有项目集合复制到新集合而不循环所有项目?我找到了一种通过 DBCursor 进行循环的方法:

...
DB db = mongoTemplate.getDb();
DBCursor cursor = db.getCollection("xxx").find();

//loop all items in collection
while (cursor.hasNext()) {
   BasicDBObject b = (BasicDBObject) cursor.next();
   // copy to new collection 
   service.createNewCollection(b);
}
...
Run Code Online (Sandbox Code Playgroud)

你能建议在java中复制而不循环所有项目吗?
(不在 mongo shell 中,使用 java 实现)Tnx。

kel*_*lee 5

在 MongoDB 2.6 中,添加了$out 聚合运算符,它将聚合结果写入集合。这提供了一种简单的方法来使用 Java 驱动程序(我使用 Java 驱动程序版本 2.12.0)将集合中的所有项目的服务器端复制到同一数据库中的另一个集合:

// 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);
Run Code Online (Sandbox Code Playgroud)

单线版:

source.aggregate(Arrays.asList((DBObject)new BasicDBObject("$out", "target")));
Run Code Online (Sandbox Code Playgroud)

根据文档,对于大型数据集(> 100MB),您可能希望使用 allowDiskUse 选项(聚合内存限制),尽管我在 >2GB 集合上运行它时没有遇到该限制,因此它可能不适用到这个特定的管道,至少在 2.6.0 中。