C# Mongo Driver IMongoDatabase RunCommand to get database stats

Muh*_*han 4 c# mongodb mongodb-.net-driver

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()");
Run Code Online (Sandbox Code Playgroud)

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()

shA*_*A.t 8

您可以使用RunCommand方法来获得这样的db.stats()结果:

var command = new CommandDocument {{ "dbStats", 1}, {"scale", 1}};
var result = db.RunCommand<BsonDocument>(command);
Run Code Online (Sandbox Code Playgroud)

结果将是这样的:

{
    "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
}
Run Code Online (Sandbox Code Playgroud)

而对于db.getCollectionNames(); 一种方法是使用此命令:

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"]);
Run Code Online (Sandbox Code Playgroud)