C# Mongo Driver IMongoDatabase RunCommand to get database stats

a 夏天 提交于 2021-02-19 02:43:05

问题


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

回答1:


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"]);



回答2:


Both upper answers did not work for me, but this did:

 var command = new BsonDocument { { "dbstats", 1 } };
        var result = db.RunCommand<BsonDocument>(command);
        Debug.WriteLine(result.ToJson());



回答3:


You can get all collection names within a db by running following code: x contains the collection names.

        String connectionString = "mongodb://your_address_here";

        var client = new MongoClient(connectionString);

        var database = client.GetDatabase("db_name_from_which_you_need_collections");

        var cnames = database.ListCollections();

        var allNames = cnames.ToList();
        foreach(var x in allNames)
        {
            Console.WriteLine(x.ToString());

        }

You can further get the standalone name by selecting x.Values.FirstOrDefault().ToString();



来源:https://stackoverflow.com/questions/40338948/c-sharp-mongo-driver-imongodatabase-runcommand-to-get-database-stats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!