MongoDB - 在java中复制集合而不循环所有项目 [英] MongoDB - copy collection in java without looping all items

查看:491
本文介绍了MongoDB - 在java中复制集合而不循环所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将所有项目集合复制到新集合,而不循环所有项目?
我找到一个方法与循环由DBCursor:

Is there a way to copy all items collection to new collection without looping all items ? I find a way with looping by 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);
}
...

所有项?

(不是在mongo shell中,使用java实现)
Tnx。

Can you suggest do copy in java without looping all items ?
(Not In the mongo shell, with java implemintation) Tnx.

推荐答案

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

In MongoDB 2.6, the $out aggregation operator was added which writes the results of the aggregation to a collection. This provides a simple way to do a server-side copy of all the items in a collection to another collection in the same database using the Java driver (I used Java driver version 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);

一行版本:

source.aggregate(Arrays.asList((DBObject)new BasicDBObject("$out", "target")));

根据文档,对于大型数据集(> 100MB),您可能需要使用allowDiskUse选项汇总内存限制),虽然我没有运行到这个限制,当我在一个> 2GB的集合,因此它可能不适用于这个特定的管道,至少在2.6.0。

According to the docs, for large datasets (>100MB) you may want to use the allowDiskUse option (Aggregation Memory Restrictions), although I didn't run into that limit when I ran it on a >2GB collection, so it may not apply to this particular pipeline, at least in 2.6.0.

这篇关于MongoDB - 在java中复制集合而不循环所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆