简体   繁体   中英

How to copy mongo database with all it's collection using c# driver?

I am trying to copy a mongo database using copydb command using c# driver. But it's just create the target db with no collection inside. When i run the command directly with the mongo shell it work fine.

These is the c# code:

var db = mongo.GetServer().GetDatabase("admin");
var command = new CommandDocument(new BsonElement("copydb", 1),
                                  new BsonElement("fromdb", "db1"),
                                  new BsonElement("todb", "db2")
                                 );
var result = db.RunCommand(command);

Its not copy the collections of db1.

These is the command i run into mongo shell and work fine:

db.runCommand({copydb:1, fromdb:"db1", todb:"db2"})

What am i missing?

Try following :

var result = db.RunCommand(
            new CommandDocument(new BsonElement("copydb", 1),
                new BsonElement("fromhost", "localhost"),
                new BsonElement("fromdb", "sourcedb"),
                new BsonElement("todb", "targetdb")));

Next code works. It's C# MongoDB.Driver 2.0

var database = mongoClient.GetDatabase("admin");
var command = @"{ copydb: 1, fromhost: 'localhost', fromdb: 'from', todb: 'toDbName'}";
await database.RunCommandAsync<BsonDocument>(BsonDocument.Parse(command));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM