Joey Baruch
Joey Baruch

Reputation: 5249

How to copy a mongodb collection with the java driver (v3.4)

I'm trying to copy an existing collection to a new collection within the same database, emulating the behavior of running db.source.aggregate({"$out":"target"}); in the shell.

On older versions of mongodb and the java driver, it was possible to do (as seen 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);

but since mongo 3.0.0, the writers are moving away from DBCollection and onto MongoCollection and others that don't have the same functionalities, specifically for .aggregate(List<DBObject>).

I've tried the following options, none of which had any effect:

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

Sadly, I don't understand aggregate operations well enough to figure this out.

Is there any similar way to do this with the java driver and mongo 3.4?
Are there any other ways that'll cause the copy serverside?

Thanks

Upvotes: 1

Views: 1629

Answers (3)

Xushipeng
Xushipeng

Reputation: 1

source.aggregate(Arrays.asList(out("<OutputcollectionName>"))).toCollection();

Upvotes: -1

Supreet ST
Supreet ST

Reputation: 21

Add .toCollection() .. that should work without noOps block

Upvotes: 2

JayKrish
JayKrish

Reputation: 947

You can try this:

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

use the following import statement:

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

Upvotes: 3

Related Questions