Search code examples
mongodbmongodb-querymongodb-.net-driver

MongoDB C# Driver: Execute Database Method through the SDK?


I want to be able to execute a database method using the C# SDK (2.2.4). Take db.version() for example.

I've tried to play around with Database.RunCommand, but with no luck:

var command = new BsonDocumentCommand<BsonDocument>(new BsonDocument
{
    { "version", 1 }
});

var versionResult = Database.RunCommand(command);

Exception:

MongoDB.Driver.MongoCommandException: Command version failed: no such command: 'version', bad cmd: '{ version: 1 }'.


Solution

  • There's not always a direct mapping between the shell database methods you link to and the underlying database commands that are available via Database.RunCommand. The available commands are listed here, and to get the server version you could use the serverStatus command:

    var version = db.RunCommand<dynamic>(new BsonDocument("serverStatus", 1)).version;