1

I want to be able to run any MongoDB command from C#. I know that this can be done. I start with a simple example, instead of using the dropDatabase method from the C# driver I am trying to drop a database using the db.runCommand method as follows.

I have tried in two ways, passing the command as a string and also passing the command as a BsonDocument but nothing is working and I don't have any clues where I'm wrong even after researching on the internet I cannot find a suitable example.

I'm having a really hard time to identify why this piece of code is not working.

Command passed as a string:

database.RunCommand<string>("{dropdatabase : 1}");

Command passed as a BSON document:

var command = new BsonDocument { {"dropdatabase", "1" } };
var execute = database.RunCommand<BsonDocument>(command);
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
user2307236
  • 665
  • 4
  • 19
  • 44
  • What is the result returned when you execute the command? It looks like you aren't using the proper case in your code examples: the command is `dropDatabase`: https://docs.mongodb.com/manual/reference/command/dropDatabase/. With the all-lowercase example your code would likely get an error like `"no such command: dropdatabase"`. – Stennie Jul 30 '16 at 08:51

1 Answers1

4

You can use a JsonCommand like this:

var command = new JsonCommand<BsonDocument>("{ dropDatabase: 1 }");
db.RunCommand(command);

or use a CommandDocument like this:

var command = new CommandDocument("dropDatabase", 1);
db.RunCommand<BsonDocument>(command);
shA.t
  • 16,580
  • 5
  • 54
  • 111