C# Mongo Driver IMongoDatabase RunCommand to get database stats
c#, mongodb, mongodb-.net-driver
Solution
You can use `RunCommand` method to get `db.stats()` results like this:
var command = new CommandDocument {{ "dbStats", 1}, {"scale", 1}};
var result = db.RunCommand<BsonDocument>(command);
Result will be like this:
{
"db" : "Test",
"collections" : 7,
"objects" : 32,
"avgObjSize" : 94.0,
"dataSize" : 3008,
"storageSize" : 57344,
"numExtents" : 7,
"indexes" : 5,
"indexSize" : 40880,
"fileSize" : 67108864,
"nsSizeMB" : 16,
"dataFileVersion" : {
"major" : 4,
"minor" : 5
},
"extentFreeList" : {
"num" : 0,
"totalSize" : 0
},
"ok" : 1.0
}
And for `db.getCollectionNames()`; a way is to use this command:
var command = new CommandDocument { { "listCollections", 1 }, { "scale", 1 } };
var result = db.RunCommand<BsonDocument>(command);
// and to clear extra details
var colNames = result["cursor"]["firstBatch"].AsBsonArray.Values.Select(c => c["name"]);
Problem
`IMongoDatabase` does not support `db.GetStats();` which is deprecated in new version. I want to try alternate approach to get database stats. I use the following code to run command as we can get the stats from shell: ``` var client = new MongoClient("mongodb://localhost:27017/analytics"); var db = client.GetDatabase("analytics"); var stats = db.RunCommand<BsonDocument>("db.stats()"); var collectionNames = db.RunCommand<BsonDocument> ("db.getCollectionNames()"); ``` I am getting following error here: JSON reader was expecting a value but found 'db'. Need help to execute the command on Mongo database using ژ# driver, like: - `db.stats()` - `db.getCollectionNames()`