mongodb复制集连接Java,MongoDB - 在java中复制集合而不循环所有项目

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);

}

...

Can you suggest do copy in java without looping all items ?

(Not In the mongo shell, with java implemintation)

Tnx.

解决方案

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 ops = new ArrayList();

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);

The one-liner version:

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值