Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the C# driver Is their a better way to duplicate and copy a MongoDB collection?

I have multiple MongoDB servers for dev, staging and production and I want to automate some of the deploy process from Dev->Staging and Staging->Live. Duplicating collections by hand means using the rather fabulous MongoVUE tool (http://www.mongovue.com/) but clearly that's not an ideal solution for automation!

So from within the C# Driver, is there a way to duplicate a collection on the same server? And is there a way to copy an entire collection (with indices intact) to a different server?

I've tried looping through collections, retrieving documents from server A then inserting them into server B. This approach feels clumsy, lengthy and error prone. Is there a better way?

Thanks!

like image 325
Chris Masterton Avatar asked Sep 17 '25 09:09

Chris Masterton


1 Answers

You can use the "copyDB" database command, which is described at: http://docs.mongodb.org/manual/reference/command/copydb/#dbcmd.copydb

In C#, you would run the following on the destination server:

var command = new CommandDocument(new BsonElement("copydb", 1),
                                  new BsonElement("fromhost", mydbserver),
                                  new BsonElement("fromdb", sourcedb),
                                  new BsonElement("todb", targetdb));
var client = new MongoClient(mydbserver);
var server = client.GetServer();
var db = server.GetDatabase("admin");
db.RunCommand(command);
like image 105
Derick Avatar answered Sep 19 '25 00:09

Derick